week reference to autoreleased object not getting deallocated in case of NSString

帅比萌擦擦* 提交于 2019-12-04 04:51:48

问题


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



来源:https://stackoverflow.com/questions/29204702/week-reference-to-autoreleased-object-not-getting-deallocated-in-case-of-nsstrin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!