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时,可能发生变化
.引起数据的错乱;毕竟两者的使用场景是不同的,其实是没有可比性的.
网友评论