美文网首页
iOS---strong和copy的区别

iOS---strong和copy的区别

作者: 彬至睢阳 | 来源:发表于2018-08-10 09:31 被阅读0次

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong)NSString *strStrong;

@property (nonatomic,copy)NSString *strCopy;

@property (nonatomic,strong)NSDictionary* dicStrong;

@property (nonatomic,copy) NSDictionary* dicCopy;

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    self.title=@"测试";

    self.view.backgroundColor = [UIColor whiteColor];

    NSMutableString *testString = [NSMutableString stringWithString:@"str is ?"];

    self.strStrong= testString;

    self.strCopy= testString;

    NSLog(@"1----%@-----%@",self.strStrong,self.strCopy);

    //1----str is ?-----str is ?

    [testStringappendString:@"strong"];

    NSLog(@"2----%@-----%@",self.strStrong,self.strCopy);

    //2----str is ?strong-----str is ?

    //重点:如果是strong,传到person里面的数值会根据所传值的改变而改变,而copy并不会如此,保证了数据的一致性。

   /*

    @property (nonatomic, strong) NSString *stringStrong 的setter方法是:

    那么如上strong和copy在属性上的区别就是关于copy在setter方法最终是拷贝了参数内容,创建了一块新的内存,所以无论老地址里面的数据如何改变,对新数据并没有影响。而strong,本质是retain,只是copy了指针而已。

     不可变数据无论外部如何变化,其实copy与strong并无区别

    copy 与 mutableCopy(深拷贝)对于NSArray,NSMutableArray,NSDictionary,NSMutableDictionary

    @property (nonatomic,copy)NSString *strCopy;  的setter方法实际是:

    - (void)setStrCopy:(NSString *)strCopy{

    [_strCopy release];

    _strCopy = [strCopy copy];//指针和值全部拷贝

    }

    @property (nonatomic,strong)NSString *strStrong; 的setter方法实际是:

    - (void)setStrStrong:(NSString *)strStrong{

    [_strStrong release];

    _strStrong = [strStrong retain];

    _strStrong = strStrong;//只拷贝值,还是同一个内存地址

    }

    */

    NSMutableDictionary* mutDic = [[NSMutableDictionary alloc]initWithDictionary:@{@"123":@"123"}];

    self.dicCopy= mutDic;

    self.dicStrong= mutDic;

    NSLog(@"3--%@--- %@",self.dicStrong,self.dicCopy);

//    3--{

//        123 = 123;

//    }--- {

//        123 = 123;

//    }

    [mutDicaddEntriesFromDictionary:@{@"2":@"2"}];

    NSLog(@"4--%@--- %@",self.dicStrong,self.dicCopy);

//    //4--{

//    123 = 123;

//    2 = 2;

//}--- {

//    123 = 123;

//}

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

注意:

copy与strong:相同之处是用于修饰表示拥有关系的对象。不同之处是strong复制是多个指针指向同一个地址,而copy的复制是每次会在内存中复制一份对象,指针指向不同的地址。NSString、NSArray、NSDictionary等不可变对象用copy修饰,因为有可能传入一个可变的版本,此时能保证属性值不会受外界影响。若用strong修饰NSArray,当数组接收一个可变数组,可变数组若发生变化,被修饰的属性数组也会发生变化,也就是说属性值容易被篡改;若用copy修饰NSMutableArray,当试图修改属性数组里的值时,程序会崩溃,因为数组被复制成了一个不可变的版本。

相关文章

网友评论

      本文标题:iOS---strong和copy的区别

      本文链接:https://www.haomeiwen.com/subject/wkpmmftx.html