ios - - (id)copyWithZone: 和 + (id)copyWithZone: 的区别???
大家讲道理
大家讲道理 2017-04-17 17:46:33
0
3
453

两个协议:
// @protocol NSCopying
// - (id)copyWithZone:(nullable NSZone *)zone;
// @end

// @protocol NSMutableCopying
// - (id)mutableCopyWithZone:(nullable NSZone *)zone;
// @end

下面是NSObject.h 头文件中的:
// + (id)copyWithZone:(struct _NSZone *)zone OBJC_ARC_UNAVAILABLE;
// + (id)mutableCopyWithZone:(struct _NSZone *)zone OBJC_ARC_UNAVAILABLE;

// - (id)copy;
// - (id)mutableCopy;

问题:
(1)- (id)copyWithZone: 和 + (id)copyWithZone:的区别,+ (id)copyWithZone:一般用在什么地方???
(2)我尝试[NSString copy]; 直接用NSString类执行copy操作,也不会报错,- (id)copy;不是对象方法吗???为什么可以当作类方法来使用???
(3)自定义单例类的时候,一般重写- (id)copyWithZone: 还是 + (id)copyWithZone:,求大神指教???

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all (3)
洪涛

Official document『This method exists so class objects can be used in situations where you need an object that conforms to the NSCopying protocol. For example, this method lets you use a class object as a key to an NSDictionary object. You should not override this method.』
After reading the above, it is actually very clear.
+copy and +copyWithZone exist to serve class objects (class obj) so that class objects can be inserted into containers. And because only one copy of a class object can exist globally, the +copy and +copyWithZone methods simply return self. NSObject implements the copy class method, but it is not in the header file.
Knowing this, the problems are very simple. All you need to do is consider object methods.

    大家讲道理

    + is a class method, - is an object method
    + can be called directly using the class name
    - if necessary, it must be called with the instantiated class object
    The singleton class is overridden by the held class object - that’s it

      巴扎黑

      Question (3)

      - (id)copyWithZone:(NSZone *)zone { return self; }
      - (id)mutableCopyWithZone:(NSZone *)zone { return self; }
        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!