NSString 初始化内存管理状态

NSString *string = @"ABC";

NSString中initWithFormat和stringWithFormat会生成新的对象。

stringWithString和initWithString不会生成新的对象,生成的对象地址就是常量 ABC 的地址。

如下截图,代码在下方喔;

NSString 初始化内存管理状态_第1张图片

- (void)viewDidLoad {

[super viewDidLoad];

NSString *tempString = @"LOL";

NSLog(@"LOL常量内存地址=%p ----- tempString内存地址=%p", @"LOL", tempString);

NSLog(@"%@", [self compareAddress:@"LOL" otherAddress:tempString type:@"=赋值"]);

NSString *str0 = [NSString stringWithString:tempString];

NSLog(@"%@", [self compareAddress:@"LOL" otherAddress:str0 type:@"stringWithString"]);

NSString *str1 = [NSString stringWithFormat:@"LOL"];

NSLog(@"%@", [self compareAddress:@"LOL" otherAddress:str1 type:@"stringWithFormat"]);

NSString *str2 = [[NSString alloc] initWithFormat:@"LOL"];

NSLog(@"%@", [self compareAddress:@"LOL" otherAddress:str2 type:@"initWithFormat"]);

NSString *str3 = [[NSString alloc] initWithString:tempString];

NSLog(@"%@", [self compareAddress:@"LOL" otherAddress:str3 type:@"initWithString"]);

}

- (NSString *)compareAddress:(id)addressOne otherAddress:(id)address type:(NSString *)type  {

if ([[NSString stringWithFormat:@"%p", addressOne] isEqual:[NSString stringWithFormat:@"%p", address]]) {

return [NSString stringWithFormat:@"%@方法生成的字符串地址都一样, %@ = %p", type, address, address];

} else {

return [NSString stringWithFormat:@"%@方法生成的字符串地址不一样,地址为%p === 地址为%p", type, addressOne, address];

}

}

你可能感兴趣的:(NSString 初始化内存管理状态)