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?
As CRD said, strings have all sorts of optimizations that alter their memory management. Repeat this exercise with your own custom
NSObjectsubclass and you should see traditional object lifecycle behaviors.Your expected output for the
assignproperty is incorrect. You should expect that to have a dangling pointer to the deallocated object. Theassignreference is not set tonilautomatically when the object is deallocated. Theweakreference will, but theassignreference will not.Thus, if you have properties like so:
And then do:
At the second
NSLogstatement, thestrongandweakreferences will benil, but theassignreference will not.