week reference to autoreleased object not getting

2019-02-27 12:35发布

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,
}

1条回答
Evening l夕情丶
2楼-- · 2019-02-27 13:12

Constant strings are never released. There are other objects that are never released, like certain NSNumber objects (on 64 bit versions, most NSNumber objects).

It makes me wonder what you are up to. What do you want to do if that NSString* becomes nil (which it won't)?

查看更多
登录 后发表回答