iOS NSString copy、strong区别代码案例

2017-03-29  本文已影响41人  ThaiLanKing
@property (nonatomic, copy) NSString *mCopyStr;
@property (nonatomic, strong) NSString *mStrongStr;

- (void)testDifferenceBetweenCopyAndStrong
{
    NSMutableString *mStr = [NSMutableString stringWithString:@"testMStr"];
    self.mCopyStr = mStr;
    self.mStrongStr = mStr;
    [mStr appendString:@"Add"];
    
    NSLog(@"copyStr = %@, strongStr = %@", self.mCopyStr, self.mStrongStr);
}

最后的输出结果是:

copyStr = testMStr, strongStr = testMStrAdd

通常情况下我们将一个string赋值给一个新string后是不希望原值的变化影响到新string的,为了避免不可预料的错误,string最好声明为copy属性。

上一篇下一篇

猜你喜欢

热点阅读