標籤:
Objective-c中某個執行個體對象是否支援copy操作,要看這個對象是否實現了NSCopying協議:
@protocol NSCopying- (id)copyWithZone:(NSZone *)zone;@end
對於mutableCopy操作對應的有NSMutableCopying協議:
@protocol NSMutableCopying- (id)mutableCopyWithZone:(NSZone *)zone;@end
我們看到NSObject介面裡面是有copy和mutableCopy方法的,是不是說我們上面說的必須遵循協議的說法是錯誤的呢?
@interface NSObject <NSObject> { Class isa OBJC_ISA_AVAILABILITY;}........- (id)copy;- (id)mutableCopy;.......@end
我們來做一個測試:
//test NSObject copy NSObject *originObject = [[NSObject alloc] init]; NSObject *copiedObject = [originObject copy]; NSObject *mutableCopiedObject = [originObject mutableCopy]; NSLog(@"%@, %@, %@", originObject, copiedObject, mutableCopiedObject);
當代碼執行到[originObject copy]時crash了,提示NSObject並沒有實現NSCopying協議的方法,
2015-04-27 14:16:56.680 NSLockTest[52535:816047] -[NSObject copyWithZone:]: unrecognized selector sent to instance 0x79f909b0
理解Objective-c中的copy