简体   繁体   English

分配和弱

[英]Assign And Weak

I want to look a difference between assign and weak.So I run this code below: 我想看看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

I think it should output like this: 我认为它应该像这样输出:

str = 0x0 str = 0x0

assignString = 0x0 assignString = 0x0

weakString = 0x0 weakString = 0x0

str = (null) str =(null)

assignString = (null) assignString =(null)

weakString = (null) weakString =(null)

But I get this output: 但我得到这个输出:

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

str = 0x0 str = 0x0

assignstr = 0x100002078 assignstr = 0x100002078

weakStr = 0x100002078 weakStr = 0x100002078

str = (null) str =(null)

assignStr = i'm test string assignStr =我是测试字符串

weakString = i'm test string weakString =我是测试字符串

It's there something wrong with my code? 我的代码有问题吗?

  1. As CRD said, strings have all sorts of optimizations that alter their memory management. 正如CRD所说,字符串具有各种优化,可以改变其内存管理。 Repeat this exercise with your own custom NSObject subclass and you should see traditional object lifecycle behaviors. 使用您自己的自定义NSObject子类重复此练习,您应该看到传统的对象生命周期行为。

  2. Your expected output for the assign property is incorrect. 您对assign属性的预期输出不正确。 You should expect that to have a dangling pointer to the deallocated object. 你应该期望有一个指向解除分配对象的悬空指针。 The assign reference is not set to nil automatically when the object is deallocated. 取消分配对象时, assign reference不会自动设置为nil The weak reference will, but the assign reference will not. weak引用将会,但assign引用不会。

Thus, if you have properties like so: 因此,如果你有这样的属性:

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

And then do: 然后做:

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);

At the second NSLog statement, the strong and weak references will be nil , but the assign reference will not. 在第二个NSLog语句中, strong引用和weak引用将为nil ,但assign引用不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM