还是以例子来说明吧。新建一个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
原文:http://blog.csdn.net/lvxiangan/article/details/44627873