Why temp
object is not released and set to nil even though it is declared as __week
. But in case of Person object its working as expected. Do NSString
objects memory life cycle is handled differently? How?
@interface Person : NSObject
@property(nonatomic, strong) NSString *name;
- (instancetype)initWithName:(NSString *)name;
+ (Person *)personWithName:(NSString *)name;
@end
@implementation Person
- (instancetype)initWithName:(NSString *)name {
if (self = [super init]) {
self.name = name;
}
return self;
}
+ (Person *)personWithName:(NSString *)name {
return [[self alloc] initWithName: name];
}
@end
- (void)viewDidLoad {
__weak NSString *temp;
@autoreleasepool {
NSMutableArray *data = [[NSMutableArray alloc] initWithObjects:@"firstString", @"secondString", nil];
temp = data[0];
[data removeObjectAtIndex:0];
}
NSLog(@"%@", temp);//prints firstString instead of null
__weak Person *person ;
@autoreleasepool {
NSMutableArray *persons = [[NSMutableArray alloc] initWithObjects:[Person personWithName:@"Steve"], [Person personWithName:@"Harry"], nil];
person = persons[0];
[persons removeObjectAtIndex:0];
}
NSLog(@"%@", person.name);//prints null as expected because person object will be deallocated,
}