zoukankan      html  css  js  c++  java
  • Object copying

    NSObject类定义了copy方法,但这只是一个convinence method for classes who adopt NSCopying协议。如果某个类没有实现copyWithZone:,那调用copy方法会抛出异常。NSObject类的方法mutableCopy对应于NSMutableCopying protocol的方法mutableCopyWithZone:

    NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement the copyWithZone: method. A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.

    如果一个类考虑adopt NSCopying协议,那还要考虑是否应该选择NSMutableCopying?如何选择呢?先看官方文档。

    The returned object is implicitly retained by the sender, who is responsible for releasing it. The copy returned is immutable if the consideration “immutable vs. mutable” applies to the receiving object; otherwise the exact nature of the copy is determined by the class.

    也就是说,对于一个类/对象来说,在考虑adopt NSCopying或者NSMutableCopying协议时,需要考虑receiving object是由有“immutable vs. mutable”之分,如果有此区分,那copyWithZone:返回的是immutable的copy,mutable的copy由mutableCopyWithZone:实现。如果没有“immutable vs. mutable”之分,那就不要实现mutableCopyWithZone:, 并且从通常意义上来考虑copy行为是什么样的,毕竟每个类的Copy行为是不一样的,比如有的是做shallow copy,有的是做deep copy,或者部分shallo,部分deep,完全依需求而定。

  • 相关阅读:
    迭代模式
    HackSeven Canvas上的动画
    模板模式
    适配器模式
    豆瓣推荐纪录片
    二手手机十分管用的检查方法
    传参的四种方法
    守夜人誓言+考研誓言
    网络小说分享
    阿里巴巴Java开发手册(详尽版) pdf
  • 原文地址:https://www.cnblogs.com/whyandinside/p/2958152.html
Copyright © 2011-2022 走看看