关于NSString

一个经典的面试题,在viewDidLoad创建的string,什么时候释放?

__weak NSString *string_weak_ = nil;
__weak NSObject *object_weak_ = nil;

- (void)viewDidLoad
{
    [super viewDidLoad];

//   NSString *sd = @"1234567";                                   //(NSCFConstantString:0x0000000109278150)
//   NSString *sd = [NSString stringWithFormat:@"123456789"];  //(NSTaggedPointerString:0xa1ea1f72bb30ab19)
    NSString *sd = [NSString stringWithFormat:@"123456789abcdefg"];       //(NSCFString:0x000061000005ea50)
//  NSString *sd = [@"sdf" stringByAppendingString:@"adsdsfds"];          //(NSCFString:0x00006000000427c0)
    string_weak_ = sd;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"viewWillAppear %@", string_weak_);
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"viewDidAppear %@", string_weak_);
}

NSCFConstantString静态存储区,不会释放
NSTaggedPointerString 内容存储在指针内,不会释放
第一种的NSCFString,由于stringWithFormat,加入自动释放池,等到下一个runloop释放
第二种的NSCFString和object一样,会自动插入release,viewDidLoad结束释放

你可能感兴趣的:(关于NSString)