【问题标题】:week reference to autoreleased object not getting deallocated in case of NSString在 NSString 的情况下,对自动释放对象的周引用不会被释放
【发布时间】:2015-03-23 06:55:55
【问题描述】:

为什么temp 对象没有被释放并设置为零,即使它被声明为__week。但是如果是 Person 对象,它会按预期工作。 NSString 对象内存生命周期的处理方式是否不同?怎么样?

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

【问题讨论】:

  • 尝试记录 person 对象,检查是否给你 null。 NSLog(@"%@", 人);
  • 这可能是因为您正在使用常量字符串进行测试。尝试构建 NSString 对象,看看是否可行。

标签: objective-c automatic-ref-counting


【解决方案1】:

永远不会释放常量字符串。还有其他对象永远不会被释放,例如某些 NSNumber 对象(在 64 位版本上,大多数 NSNumber 对象)。

这让我想知道你在做什么。如果 NSString* 变为 nil(它不会),你想做什么?

【讨论】:

    猜你喜欢
    • 2011-04-08
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多