ARC模式新加入了strong修饰符,strong相当于MRC下的Retain,不过strong是强引用.下面介绍一下strong和copy的区别,具体看代码
@interface People : NSObject
@property (nonatomic,copy)NSString *name;
@end
@implementation People
@synthesize name;
@end
@interface ViewController ()
@property (nonatomic,copy)NSArray *copyarr;
@property (nonatomic,weak)NSArray *strongarr;
@end
People *p1 = [[People alloc] init];
p1.name = @"张三";
People *p2 = [[People alloc] init];
p2.name = @"李四";
NSMutableArray *arr = [NSMutableArray arrayWithArray:@[p1,p2]];;
self.copyarr = arr;
self.strongarr = arr;
People *p3 = [[People alloc] init];
p3.name = @"王五";
[arr addObject:p3];
再将p3加入arr数组.copy会将数组复制一份,strong则是将指针指向数组,为了验证,添加打印
NSLog(@"copyarr:%p",self.copyarr);
NSLog(@"strongarr:%p",self.strongarr);
NSLog(@"arr:%p",arr);
for (People *p in self.copyarr) {
NSLog(@"copyarr:%@,%p",p.name,p);
}
for (People *p in self.strongarr) {
NSLog(@"strongarr:%@,%p",p.name,p);
}
打印结果如下
2015-12-29 10:28:20.134 Testdemo2Delete[1174:43789] copyarr:0x7fb1d9579e00
2015-12-29 10:28:20.134 Testdemo2Delete[1174:43789] strongarr:0x7fb1d9510260
2015-12-29 10:28:20.135 Testdemo2Delete[1174:43789] arr:0x7fb1d9510260
2015-12-29 10:28:20.135 Testdemo2Delete[1174:43789] copyarr:张三,0x7fb1d9514c00
2015-12-29 10:28:20.135 Testdemo2Delete[1174:43789] copyarr:李四,0x7fb1d95158d0
2015-12-29 10:28:20.135 Testdemo2Delete[1174:43789] strongarr:张三,0x7fb1d9514c00
2015-12-29 10:28:20.135 Testdemo2Delete[1174:43789] strongarr:李四,0x7fb1d95158d0
2015-12-29 10:28:20.135 Testdemo2Delete[1174:43789] strongarr:王五,0x7fb1d9578500
可以看到,copy修饰的数组地址和arr(源数组)的地址不一样,并且copyarr中只用p1和p2,
可以证明copy是将源数组copy了一份(重新开辟了空间)并将指针指向新的空间;strong的地址和arr的地址一样,可以知道,strong指向的还是源数组,对象是一样的.