首页 > - (id)copyWithZone: 和 + (id)copyWithZone: 的区别???

- (id)copyWithZone: 和 + (id)copyWithZone: 的区别???

两个协议:
// @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:,求大神指教???


+是类方法,-是对象方法
+可以使用类名直接调用
-必要要用实例化后的类对象调用
单例类是持有的类对象重写-就可以了


问题 (3)

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
    return self;
}

官方文档『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.』
看了上面这个,其实已经很清楚了。
+copy、+copyWithZone的存在是为类对象(class obj)服务,以便让类对象能够被插入到容器中。又因为类对象全局只能存在一份,所以+copy、+copyWithZone方法只是简单返回self。NSObject是实现了copy类方法的,只是没在头文件里面。
知道这些,所以,问题都很简单了,你需要做的,都只需要考虑对象方法。

【热门文章】
【热门文章】