NSString *string = @"ABC";
NSString中initWithFormat和stringWithFormat會生成新的對象。
stringWithString和initWithString不會生成新的對象,生成的對象地址就是常量 ABC 的地址。
如下截圖,代碼在下方喔;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *tempString = @"LOL";
NSLog(@"LOL常量內(nèi)存地址=%p ----- tempString內(nèi)存地址=%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];
}
}