zoukankan      html  css  js  c++  java
  • 为啥NSString的属性要用copy而不用retain

       之前学习生活中,知道NSString的属性要用copy而不用retain,可是不知道为啥,这两天我研究了一下,然后最终明确了.

    详细原因是由于用copy比用retain安全,当是NSString的时候,其有用copy和retain都行,当用NSMutableString,那么就要用copy,NSMutableString的值不会被改动,而用retain的时候,NSMutableString的值会被改动,详细情况,能够看以下的代码:


    #import <Foundation/Foundation.h>
    
    //协议有两种方式,第一是以ing结尾形式,第二,以delegate结尾形式
    @interface person : NSObject<NSCopying>
    @property (nonatomic,copy)NSString * name;

        person * p  = [[person alloc]init];
        
        NSMutableString * name = [[NSMutableString alloc]initWithString:@"hello"];
        p.name = name;
        
        [name appendString:@" word"];
        NSLog(@"%@",p.name);

    打印后结果是

    2014-07-05 17:08:44.170 DepthCopy[1399:303] hello
    Program ended with exit code: 0


    我们能够发现打印结果还是hello;

    再看以下用retain

    #import <Foundation/Foundation.h>
    
    //协议有两种方式,第一是以ing结尾形式,第二,以delegate结尾形式
    @interface person : NSObject<NSCopying>
    
    @property (nonatomic,retain)NSString * name;

        person * p  = [[person alloc]init];
        
        NSMutableString * name = [[NSMutableString alloc]initWithString:@"hello"];
        p.name = name;
        
        [name appendString:@" word"];
        NSLog(@"%@",p.name);

    打印结果是:
    2014-07-05 17:13:19.531 DepthCopy[1412:303] hello word
    Program ended with exit code: 0

    我们能够发现结果被改变了,成为了hello word;

    所以,由以上代码,能够看出copy比retain安全,也就能明确为啥NSString的属性要用copy而不用retain了;

  • 相关阅读:
    【C语言】C语言static和extern区别
    【C语言】C语言外部变量和内部变量
    【C语言】C语言局部变量和全局变量
    【C语言】C语言常量和变量
    【C语言】C语言数据类型
    【C语言】C语言标识符
    【C语言】C语言关键字
    【C语言】外部函数和内部函数
    【C语言】C语言函数
    Android 测试 Appium、Robotium、monkey等框架或者工具对比
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5230324.html
Copyright © 2011-2022 走看看