分配和弱

时间:2015-06-17 03:39:58

标签: ios objective-c assign weak

我想看看assign和weak之间的区别。所以我在下面运行以下代码:

@interface Test : NSObject

@property(nonatomic, strong) NSString *str;
@property(nonatomic, assign) NSString *assignString;
@property(nonatomic, weak)   NSString *weakString;

@end

@implementation Test

- (id)init
{
    self =[super init];
    if (self)
    {
        self.str = @"i'm test string";

        self.assignString = self.str;
        self.weakString = self.str;

        self.str = nil;

        NSLog(@"dealloc \nstr = %p\n assignstr = %p\n weakStr = %p\n", self.str, self.assignString, self.weakString);

        NSLog(@"str = %@ \nassignStr = %@\n weakString = %@\n", self.str, self.assignString, self.weakString);
    }

    return self;
}

@end

我认为它应该像这样输出:

  

str = 0x0

     

assignString = 0x0

     

weakString = 0x0

     

str =(null)

     

assignString =(null)

     

weakString =(null)

但我得到了这个输出:

  

2015-06-17 11:22:04.676 AssignWeakDiff [4696:1897735]

     

str = 0x0

     

assignstr = 0x100002078

     

weakStr = 0x100002078

     

str =(null)

     

assignStr =我是测试字符串

     

weakString =我是测试字符串

我的代码有问题吗?

1 个答案:

答案 0 :(得分:4)

  1. 正如CRD所说,字符串具有各种优化,可以改变其内存管理。使用您自己的自定义NSObject子类重复此练习,您应该看到传统的对象生命周期行为。

  2. assign属性的预期输出不正确。你应该期望有一个指向解除分配对象的悬空指针。取消分配对象时,assign引用未自动设置为nilweak引用会,但assign引用不会。

  3. 因此,如果你有这样的属性:

    @property (nonatomic, strong) MyObject *strongObj;
    @property (nonatomic, assign) MyObject *assignObj;
    @property (nonatomic, weak)   MyObject *weakObj;
    

    然后做:

    self.strongObj = [[MyObject alloc] init];
    self.assignObj = self.strongObj;
    self.weakObj   = self.strongObj;
    
    NSLog(@"%@ %@ %@", self.strongObj, self.assignObj, self.weakObj);
    
    self.strongObj = nil;
    
    NSLog(@"%@ %@ %@", self.strongObj, self.assignObj, self.weakObj);
    

    在第二个NSLog语句中,strongweak引用将为nil,但assign引用不会。{/ p>