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

两个协议:
// @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)
洪涛

官方文件『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 that conforms to the NSCopying protocol. For example, this method lets you NSCopying protokey class example, this method lets you class class 領域. 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;
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板