希望永遠這樣睡著
1.4 strong和copy在修飾字符串時有什么區別?
- 如果使用的是NSString, 則string值的更改是不會引起原有的strongStr和copiedStr值得更改;
- (void)testCopyAndStrongString
{
NSString *string = @"I'm a old key";
// (__NSCFConstantString *) $0 = 0x0000000104f38a80 @"I'm a old key"
self.strongStr = string;
//(__NSCFConstantString *) $1 = 0x0000000104f38a80 @"I'm a old key"
self.copiedStr = string;
//(__NSCFConstantString *) $2 = 0x0000000104f38a80 @"I'm a old key"
string = @"I'm a new key";
//p string (__NSCFConstantString *) $3 = 0x0000000104f38aa0 @"I'm a new key"
//p _strongStr (__NSCFConstantString *) $4 = 0x0000000104f38a80 @"I'm a old key"
//p _copiedStr (__NSCFConstantString *) $5 = 0x0000000104f38a80 @"I'm a old key"
}
- 如果使用的是NSMutableString, 則對stringM進行追加操作是會引起原strongStr的值更改,但對于copiedStr不會引起任何的變化;
- (void)testCopyAndStrongMString
{
NSMutableString *stringM = [NSMutableString stringWithString:@"I'm a old mutable key"];
// p stringM (__NSCFString *) $0 = 0x00000002814b0840 @"I'm a old mutable key"
self.strongStr = stringM;
// p _strongStr (__NSCFString *) $1 = 0x00000002814b0840 @"I'm a old mutable key"
self.copiedStr = stringM;
// p _copiedStr (__NSCFString *) $2 = 0x00000002814b0cf0 @"I'm a old mutable key"
[stringM appendString:@"hahahha"];
// p stringM (__NSCFString *) $3 = 0x00000002814b0840 @"I'm a old mutable keyhahahha"
// p _strongStr (__NSCFString *) $4 = 0x00000002814b0840 @"I'm a old mutable keyhahahha"
// p _copiedStr (__NSCFString *) $5 = 0x00000002814b0cf0 @"I'm a old mutable key"
}
綜上兩種情況, 使用copy時,對內容的更改并不會直接引起原有值的變化
,但是使用strong時,可能發生變化
.引起數據的錯亂;畢竟兩者的使用場景是不同的,其實是沒有可比性的.