iOS基础学习

Objective-C基础学习之@property中的copy关

2017-10-27  本文已影响7人  WenJim

1.@property中的copy的作用

    @interface Person : NSObject
    @property (nonatomic, retain) NSString *name;
    @end
    NSMutableString *str = [NSMutableString stringWithFormat:@"cwj"];

    Person *p = [[Person alloc] init];
    p.name = str;
    // person中的属性会被修改
    [str appendString:@" cool"];
    NSLog(@"name = %@", p.name);
Person *p = [[Person alloc] init];
p.name = @"cwj";
Dog *d = [[Dog alloc] init];
d.age = 10;
NSLog(@"retainCount = %lu", [d retainCount]); // 1
p.pBlock = ^{
  // 报错, 调用之前就销毁了
  NSLog(@"age = %d", d.age);
};
[d release]; // 0
p.pBlock();
[p release];
    Person *p = [[Person alloc] init];
    p.name = @"cwj";
    Dog *d = [[Dog alloc] init];
    d.age = 10;
    NSLog(@"retainCount = %lu", [d retainCount]); // 1
    p.pBlock = ^{
        // 会对使用到的外界对象进行一次retain
        NSLog(@"age = %d", d.age);
        NSLog(@"retainCount = %lu", [d retainCount]); // 1
    };
    [d release]; // 1
    p.pBlock();
    [p release];

2.@property内存管理策略选择

上一篇 下一篇

猜你喜欢

热点阅读