iOS声明变量详解
內容概述:
?????? 本文主要講述了ios中多種聲明變量方式的區別與聯系,以及@interface聲明的成員變量與@property屬性的差異。最后介紹了推薦的聲明方式。
?
atany原創,轉載請注明博主與博文鏈接,3Q,未經博主允許,不得進行商業用途
http://blog.csdn.net/yang8456211/article/details/11490119
—— by atany
?
?
一、@interface與 @property的區別
?
前言:
1)@interface大括號中聲明的是“成員變量”;
2)@property聲明的是“屬性”,
@synthesize與@property配對,意義是“合成”。
成員變量與屬性的區別主要分為以下兩點:
1、在@interface中定義變量的話,為當前類的私有(private),顧名思義,這些變量只能在當前類中被訪問;而用@property聲明的變量為公有(public),可以在當前類或者其他類中被訪問。
2、使用@interface聲明的變量,使用變量名進行訪問;@property聲明的變量用“
_變量名”(不用@synthesize的方式,后面會提及),或者“self.變量名”的形式進行訪問。
?
二、多種變量聲明方式
讓我們看看下面的幾種變量聲明、以及調用方式:
1)在@interface中聲明ivar(實例變量),即成員變量,上文已經提及過,這種方式聲明的變量是私有的。
聲明:在此聲明一個NSString的變量atany。
?
@interface MethodOne : NSObject{NSString *atany; }調用:在.m文件中直接使用變量名調用即可。
?
NSLog(@"hello %@",atany);2)不在.h中聲明變量,而直接在.m的@implementation中聲明變量。
聲明:
調用:這種聲明方式與1)大同小異,使用上也相同,區別只是在interface中聲明了之后,在implementation中不能申明同名變量。
NSLog(@"hello %@",atany);3)只在.h中使用@property聲明一個變量。
聲明:
@property (nonatomic, retain) NSString *atany;調用:不在.m文件中用@synthesize合成變量的話,系統會調用Autosynthesize自動生成一個以下劃線+變量名為名稱的實例變量。
調用方式除了可以用self.atany這種形式,_atany也可以。
NSLog(@"hello %@",self.atany); NSLog(@"hello %@",_atany);?
?
4)在.h中用@property;在.m中使用@synthesize+
變量的形式合成變量。
聲明:
?
@property (nonatomic, retain) NSString *atany; @synthesize atany;調用:如果使用@synthesize合成,則不會自動生成實例變量_atany,而是atany。
?
NSLog(@"hello %@",self.atany); NSLog(@"hello %@",atany);5)在.h中用@property;在.m中使用@synthesize
變量 = _變量的形式。
聲明:
?
@property (nonatomic, retain) NSString *atany; @synthesize atany = _atany;調用:使用@synthesize 變量 = _變量的話,真正的實例變量是_atany
?
NSLog(@"hello %@",self.atany); NSLog(@"hello %@",_atany);?
注:對比4)與5)兩種方式,是不是很奇怪怎么有時候是atany有時候是_atany?
其實簡單來說@synthesize就是聲明getter、setter方法。
那么如4)這種方式。@synthesize atany 對應著getter方法為:
-(int)atany{return atany;}而5)話@synthesize atany = _atany則是:
-(int)atany{return _atany;}atany實際上是方法名,_atany才是實例變量,那么為什么oc不像java那樣有getAtany的形式呢?
???? 原因是在Object-C里的accessor(存取方法)中,不會用getAtany這種形式,因為Get這個詞在Cocoa中有著特殊的含義。如果get出現在方法名稱中,則代表了這個方法傳遞的參數會作為指針類型處理。如果亂用Get的話,也會出現一些Bug。
三、常用聲明方式與推薦聲明方式
在網上你會經常見到這種
?
@interface MethodOne : NSObject{NSString *atany; } @property (nonatomic, retain) NSString *atany;這不是重復聲明嗎?我們看看下面兩種情況:
1)在.m中使用@synthesize atany(等同于不寫@synthesize情況)
我們知道self的形式是調用getter方法,atany是直接訪問變量,那么賦值atany為atany 1,看輸出:
2013-09-09 16:39:05.422TestVar[11376:c07] hello atany 1
2013-09-09 16:39:05.422 TestVar[11376:c07] hello atany 1
說明兩者相同,也就是說@interface中的聲明是多余的。
?
2)在.m中使用@synthesize atany = _atany。
atany = @"atany 1"; _atany = @"atany 2"; NSLog(@"hello %@",self.atany); NSLog(@"hello %@",_atany); NSLog(@"hello %@",atany);輸出為:
2013-09-09 16:36:28.356TestVar[11347:c07] hello atany 2
2013-09-09 16:36:28.356TestVar[11347:c07] hello atany 2
2013-09-09 16:36:28.356TestVar[11347:c07] hello atany 1
實際上atany與_atany已經是不同的兩個實例變量了。
如上面描述而言:
?
建議是:
1.如果只是單純的private變量,那么寫在interface中與聲明在implementation里都可以。
2.如果是public屬性,就用property寫在.h文件里,在.m文件中使用@synthesize atany = _atany; 比較好。
總結
- 上一篇: JVM规范阅读-instance of
- 下一篇: DDR线长匹配与时序