iOS之變數定義使用
還是以例子來說明吧。建立一個ViewController類,Xcode為我們自動產生了兩個檔案:ViewController.h 和 ViewController.m
1、成員變數
@interface ViewController : UIViewController { // 我們稱myTest1為成員變數 BOOL myTest1;}@end
@implementation ViewController- (void)viewDidLoad { myTest1 = NO; // 不支援self.myTest1 或 [self myTest1] 的用法}@end
成員變數不使用 @synthesize,這個屬性是私人屬性,不斷給它賦值時不會改變引用計數,
成員變數預設是protected,一般情況下,非子類對象無法訪問。
2、類擴充的成員變數
@interface ViewController : UIViewController@end
// 類擴充都是放在.m檔案中@implementation的上方,否則會抱錯@interface ViewController () { // 類擴充的成員變數 BOOL myTest2;}@end@implementation ViewController- (void)viewDidLoad { myTest2 = YES; // 用法與1相同}@end
其實這種表達方式與1是一樣的,區別在於更好的隱藏了.h檔案的私人資訊。
3、屬性變數
@interface ViewController : UIViewController// 屬性變數,若不使用 @synthesize 只表示是public屬性@property (nonatomic, copy) NSString *str1;@end
@implementation ViewController@synthesize str1 = _str1; // 合成getter和setter,放在@implementation內- (void)viewDidLoad { // 不存在的用法,直接報錯 str1 = @abc; // 正確用法1 _str1 = @abc; // 屬性名稱加前_表示公有屬性,在 @property 聲明時系統會自己加 // 正確用法2 NSString *astr = [self str1]; NSLog(@%@, astr); // 正確用法3 self.str1 = @123;}@end
4、類擴充的成員變數
@interface ViewController : UIViewController@end
@interface ViewController () // 類擴充的屬性變數 @property (nonatomic, copy) NSString *str1;@end@implementation ViewController @synthesize str1 = _str1; // 沒意義- (void)viewDidLoad { // 錯誤的用法 str1 = @345; // 正確用法 self.str1 = @123; // 正確用法 _str1 = @678; // 正確用法 NSString * aStr = [self str1];}@end
沒有@synthesize其實作用一樣,因為str1沒有經過.h對開公開。類擴充中定義的@property的作用無非是使用self.str1 和 [self str1] 更方便些。