Assign and weak
I want to see the difference between assignment and weak. So, I ran 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 am getting this output:
2015-06-17 11: 22: 04.676 AssignWeakDiff [4696: 1897735]
str = 0x0
assignstr = 0x100002078
weakStr = 0x100002078
str = (null)
assignStr = i - test string
weakString = i test string
Is there something wrong with my code?
source to share
-
As CRD said, strings have all sorts of optimizations that alter memory management. Repeat this exercise with your own subclass
NSObject
and you should see the behavior of the normal object lifecycle. -
Your expected result for the property is
assign
not correct. You should expect it to have a dangling pointer to the freed object. The link isassign
notnil
automatically set when the object is released. Thereweak
will be a link , but no linkassign
.
Thus, if you have properties like this:
@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);
In the second expression , there will be NSLog
links , but there will be no link .strong
weak
nil
assign
source to share