本文介绍了在NSString的情况下,对自动释放对象的一周引用未释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么即使声明为__week,也不会释放temp对象并将其设置为nil.但是在Person对象的情况下,其工作将按预期进行. NSString对象的内存生命周期是否有不同的处理方式?怎么样?

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

推荐答案

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

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

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

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

这篇关于在NSString的情况下,对自动释放对象的一周引用未释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 10:19