zoukankan      html  css  js  c++  java
  • iOS copy 和 mutableCopy 学习

    (参考 iOS 52个技巧学习心得笔记 第二章 对象 , 消息, 运行期)的对象部分

    关于Copy  有个经典问题”大部分的时候NSString的属性都是copy,那copy与strong的情况下到底有什么区别呢” 或者说”为什么 NSString 类型成员变量的修饰属性用 copy 而不是 strong (或 retain ) ?”

    明显 第一句比第二句 严谨多了.

    @property (strong,nonatomic) NSString *strongString; & @property (copy,nonatomic) NSString *copyString;

    正确理解 应该是区分这两种表达方式的区别

    不同写法,权限 不同 安全级别不同.

    (1)如果是 一个 普通NSString 赋值给copyString 和 strongString  没区别,  copy 是浅拷贝, 对于二者的被赋值 都是指针引用

    (2)如果是一个可变字符串NSMutableString 赋给copyString 和 strongString ,对于copyString则是深复制 不会跟着源头的变化而变化.而strongString 还是浅复制 是指针引用 会随着源头的变化而变化

    其二,copy 和 mutableCopy

    copy 是浅复制 , 简单指针引用,随源头的变化而变化 

    multableCopy 是深复制,是创建了一个新的对象,不会随着源头变化而变化

    以下 是一位网友得到的 的Runtime源码中NSMutableString.m实例方法
    
    -(id)copy {
        return [[NSString alloc] initWithString:self];
    }
      -(id)copyWithZone:(NSZone*)zone {
        return [[NSString allocWithZone:zone] initWithString:self];
    }
    对于 NSObject.mm方法
    
    - (id)copy {
        return [(id)self copyWithZone:nil];
    }
    - (id)mutableCopy {
        return [(id)self mutableCopyWithZone:nil];
    }
    
    NSString.m调用
    
    - (id)copyWithZone:(NSZone *)zone {
       if (NSStringClass == Nil)
            NSStringClass = [NSString class];
        return RETAIN(self); 
    }
    - (id)mutableCopyWithZone:(NSZone*)zone {
    
        return [[NSMutableString allocWithZone:zone] initWithString:self];
    }

    由此可见 在可变类型中 copy也是深复制,但是类型变成了 普通类型,不能再增加或者减少集合元素了 

    在普通类型中 使用mutableCopy 也是深复制,类型变成了 可变类型...

    NSString *haha = @"hahahhahahah";
    NSLog(@"%p
    %p",haha,[haha mutableCopy]);

    2016-08-15 17:42:09.843 dailylife[69904:5024325] 0x10f6fa390

    0x7f8079c41f80

    Printing description of haha:

    hahahhahahah

    Printing description of haha:

    hahahhahahah

    Printing description of haha:

    (NSMutableString) NSMutableString = {

      NSString = {

        NSObject = {

          isa = __NSCFConstantString

        }

      }

    }

    同理:NSString  NSArray NSDictionary  

    参考:

    https://searchcode.com/file/68838008/jni%20w:%20itoa%20runtime%20and%20allocator/Foundation/NSMutableString.m

    http://ios.jobbole.com/87987/

  • 相关阅读:
    HDU 3833 YY's new problem ()
    从文件读入16进制数转化为10进制数再输出到文件中
    UESTC 1215 (思维题 旋转)
    HDU2067卡特兰数
    HDU2050离散数学折线分割平面
    cshell学习
    C++学习1
    QT学习1
    QT Creator常用快捷键
    Ubuntu14.04安装QT5.5
  • 原文地址:https://www.cnblogs.com/someonelikeyou/p/5773683.html
Copyright © 2011-2022 走看看