OC Property
2021-04-03 本文已影响0人
玉思盈蝶
1、四种写法的区别:
@property (nonatomic, strong) NSArray *array0;
@property (nonatomic, copy) NSArray *array1;
@property (nonatomic, strong) NSMutableArray *array2;
@property (nonatomic, copy) NSMutableArray *array3;
PS:注意以下两点:
1>修饰属性问题,小心闪退:
@property (nonatomic,copy) NSMutableArray *mutableArray;
self.mutableArray = [NSMutableArray arrayWithObject:@"111"];
// self.immutableArray = [NSArray array];
//
// NSLog(@"before mutableArray=%@,immutabxrleArray=%@",self.mutableArray,self.immutableArray);
//
// self.immutableArray = self.mutableArray;
[self.mutableArray addObject:@"222"];
上面的代码会闪退的。相当于以下代码。
NSMutableArray *arr = [NSMutableArray arrayWithObject:@"111"];
self.mutableArray = [arr copy];
正确的写法:
@property (nonatomic,copy) NSArray *immutableArray;
@property (nonatomic,strong) NSMutableArray *mutableArray;
2>
NSArray,NSDictionary,NSSet -> copy
NSMutableArray,NSMutableDictionary,NSMutableSet->strong
参考链接:
https://www.jianshu.com/p/18241d9c075c
2、class修饰属性,更方便的实现单例:
@property (nonatomic, class) ViewController *vc;
+ (ViewController *)vc {
static ViewController *instance = nil;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
+ (void)setVc:(ViewController *)vc {
}