ios - - (id)copyWithZone: 和 + (id)copyWithZone: 的区别???
大家讲道理
大家讲道理 2017-04-17 17:46:33
[iOS讨论组]

两个协议:
// @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)
PHP中文网

官方文档『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类方法的,只是没在头文件里面。
知道这些,所以,问题都很简单了,你需要做的,都只需要考虑对象方法。

大家讲道理

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

巴扎黑

问题 (3)

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
    return self;
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号