NSString 的 strong 和 copy

@interface TestString : NSObject


@property(nonatomic, strong) NSString *strongStr;

@property(nonatomic, copy) NSString *copyedStr;


@property(nonatomic, strong) NSMutableString *strongMStr;

@property(nonatomic, copy) NSMutableString *copyedMStr;


@end

修改值

  TestString *test = [[TestString alloc]init];
    
    NSMutableString *testStr = [NSMutableString stringWithFormat:@"11"];
    /// 因为 NSMutableString 为子集,所以可以赋值给 NSString 不报错
    test.strongStr = testStr;
    test.copyedStr = testStr;
    
    NSLog(@"修改值前:");
    NSLog(@"testStr=%p,valyue = %@", testStr,testStr);
    
    NSLog(@"strongStr=%p,valyue = %@", test.strongStr,test.strongStr);
    
    NSLog(@"copyedStr=%p,valyue = %@", test.copyedStr,test.copyedStr);
    
    /// 通过可变集合方式修改值,地址不变
    [testStr appendString:@"22"];
    
    NSLog(@"修改值-可变集合修改:");
    /// testStr 为可变集合时候,通过可变集合修改,地址不变,值改变
    NSLog(@"testStr=%p,valyue = %@", testStr,testStr);
    /// strongStr ,因为是浅拷贝,通过可变集合修改,也会被同时修改
    NSLog(@"strongStr=%p,valyue = %@", test.strongStr,test.strongStr);
    /// copyedStr 因为是深拷贝,通过可变集合修改,不会被修改
    NSLog(@"copyedStr=%p,valyue = %@", test.copyedStr,test.copyedStr);
    
     /// testStr 为可变集合时候,直接赋值,重新新建地址
    testStr = @"22".copy;
    NSLog(@"修改值后-直接修改:");
    /// testStr 为可变集合时候,直接地址会改变
    NSLog(@"testStr=%p,valyue = %@", testStr,testStr);
    /// strongStr ,因为是浅拷贝,直接赋值,不会被改变
    NSLog(@"strongStr=%p,valyue = %@", test.strongStr,test.strongStr);
    /// copyedStr 因为是深拷贝,直接赋值,不会被改变
    NSLog(@"copyedStr=%p,valyue = %@", test.copyedStr,test.copyedStr);
图片.png

结论

定义NSString时候,strong,copy大部分情况效果一直,但在可变集合赋值给父类非可变集合时,修改原值,会影响属性值

你可能感兴趣的:(NSString 的 strong 和 copy)