zoukankan      html  css  js  c++  java
  • 体会NSString的copy属性

    规范上NSString做属性都是写成copy的,理论上应该是复制了字符串而不是单纯的增加引用计数,其实问题只会出现在把NSMutableString赋值给NSString的时候(也就是说只有当外界把一个NSMutableString的字符串赋值给类中声明为NSString类型的属性时才产生深拷贝,其他都是浅的)

     也就是说类中的属性不管是NSString还是NSMutableString,只要外界给的类型是可变(Mutable)的,则copy属性才深拷贝

    Objective-c代码  

    1. @interface Demo : NSObject  
    • {  
    •     NSString *retainString;  
    •     NSString *copyString;  
    • }  
    •   
    • @property (nonatomic, retain)NSString *retainString;  
    • @property (nonatomic, copy)NSString *copyString;  
    • @end  
    •   
    • @implementation Demo  
    • @synthesize retainString;  
    • @synthesize copyString;  
    • -(void)dealloc  
    • {  
    •     [retainString release];  
    •     [copyString release];  
    •     [super dealloc];  
    • }  
    •   
    • @end  
    •   
    • Demo *o = [[Demo alloc] init];  
    • NSMutableString *s1 = [[NSMutableString alloc] initWithCapacity:100

    ];  

    • [s1 setString:@"fuckyou"

    ];  

    • o.retainString = s1;  
    • o.copyString = s1;  
    • NSLog(@"retain string is %@"

    , o.retainString);  

    • NSLog(@"copy string is %@"

    , o.copyString);  

    • [s1 setString:@"fuckme"

    ];  

    • NSLog(@"retain string is %@"

    , o.retainString);  

    • NSLog(@"copy string is %@"

    , o.copyString);  

     这样就可以看出,当使用retain方式的时候,NSMutableString的内容变化时,语义上应该不可变的NSString也变化了,而用copy则是始终保持赋值时的内容。

    如果对实际类型就是NSString的对象用了copy,那其实就是retain,你可以通过观察引用计数来发现,而且就语义上来说也完全没有问题,同时也避免了不需要的字符串拷贝的消耗.


  • 相关阅读:
    知识付费时代:屌丝程序员如何用技术实现
    过完年了,要不要辞职?
    程序猿不得不知道的业内“黑话”
    Go 2 Draft Designs
    11 Go 1.11 Release Notes
    10 Go 1.10 Release Notes
    09 Go 1.9 Release Notes
    win10系统电脑无法识别u盘的解决办法
    IDEA导入Git项目后右键项目找不到Git选项的解决方法
    Redis在windows下安装与配置
  • 原文地址:https://www.cnblogs.com/cnsec/p/11515769.html
Copyright © 2011-2022 走看看