我想看一下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 =(空)
AssignString =(空)
weakString =(空)

但是我得到以下输出:

2015-06-17 11:22:04.676 AssignWeakDiff [4696:1897735]
str = 0x0
Assignstr = 0x100002078
weakStr = 0x100002078
str =(空)
AssignStr =我是测试字符串
weakString =我是测试字符串

我的代码有问题吗?

最佳答案

  • 正如CRD所说,字符串具有各种优化方法,可以改变其内存管理。用您自己的自定义NSObject子类重复此练习,您将看到传统的对象生命周期行为。
  • 您对assign属性的预期输出不正确。您应该期望它有一个指向释放对象的悬挂指针。释放对象时,不会自动将assign引用设置为nilweak参考会,但assign参考不会。

  • 因此,如果您具有如下属性:
    @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引用则不是。

    07-26 00:40