• 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,完全依需求而定。

  • 相关阅读:
    HDU 5154 Harry and Magical Computer bfs
    opencv第一课 打开一个图片
    Codeforces Round #131 (Div. 1) A
    Topcoder SRM 643 Div1 250<peter_pan>
    bestcoder#23 1002 Sequence II 树状数组+DP
    bestcoder#23 1001 Sequence
    Oil Deposits 搜索 bfs 强联通
    迷宫问题 模拟队列 广度优先搜索
    Codeforces Round #283 (Div. 2) C. Removing Columns 暴力
    Codeforces Round #283 (Div. 2) B. Secret Combination 暴力水题
  • 原文地址:https://www.cnblogs.com/whyandinside/p/2958152.html
Copyright © 2020-2023  润新知