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] 更方便些。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#import "ViewController.h"
@implementation ViewController {
NSString *str2; // 也是成员变量,只是放在@implemetation中的变量无法被子类继承
}
// 报错
@synthesize str2 = _str2;
- (void)viewDidLoad {
// 正确用法
str2 = @"234";
// 报错
_str2 = @"345";
// 报错
self.str2 = @"";
}
@end