week reference to autoreleased object not getting

2019-02-27 12:55发布

问题:

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:

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)?