Assign And Weak

166 views Asked by At

I want to look a difference between assign and weak.So I run this code below:

@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

assignString = 0x0

weakString = 0x0

str = (null)

assignString = (null)

weakString = (null)

But I get this output:

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

str = 0x0

assignstr = 0x100002078

weakStr = 0x100002078

str = (null)

assignStr = i'm test string

weakString = i'm test string

It's there something wrong with my code?

1

There are 1 answers

2
Rob On BEST ANSWER
  1. As CRD said, strings have all sorts of optimizations that alter their memory management. Repeat this exercise with your own custom NSObject subclass and you should see traditional object lifecycle behaviors.

  2. Your expected output for the assign property is incorrect. 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. The weak reference will, but the assign reference will not.

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.