還是以例子來說明吧。新建一個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
成員變量默認是protected,一般情況下,非子類對象無法訪問。
2、類擴展的成員變量
@interface ViewController : UIViewController @end
// 類擴展都是放在.m文件中@implementation的上方,否則會抱錯
@interface ViewController () {
// 類擴展的成員變量
BOOL myTest2;
}
@end
@implementation ViewController
- (void)viewDidLoad {
myTest2 = YES; // 用法與1相同
}
@end
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
@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