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

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

大家讲道理
大家讲道理

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

membalas semua(3)
洪涛

Dokumen rasmi "Kaedah ini wujud supaya objek kelas boleh digunakan dalam situasi di mana anda memerlukan objek yang mematuhi protokol NSCopying. Sebagai contoh, kaedah ini membolehkan anda menggunakan objek kelas sebagai kunci kepada objek NSDictionary. Anda harus tidak mengatasi kaedah ini.』
Selepas membaca di atas, ia sebenarnya sangat jelas.
copy dan copyWithZone wujud untuk menyediakan objek kelas (obj kelas) supaya objek kelas boleh dimasukkan ke dalam bekas. Dan kerana hanya satu salinan objek kelas boleh wujud secara global, kaedah copy dan copyWithZone hanya mengembalikan diri. NSObject melaksanakan kaedah kelas salinan, tetapi ia tidak terdapat dalam fail pengepala.
Mengetahui perkara ini, masalahnya sangat mudah. ​​Anda hanya perlu mempertimbangkan kaedah objek.

大家讲道理

ialah kaedah kelas, - ialah kaedah objek
boleh dipanggil terus menggunakan nama kelas
- mesti dipanggil dengan objek kelas instantiated
Kelas tunggal ditindih oleh kelas yang dipegang objek -Itu sahaja

巴扎黑

Soalan (3)

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
    return self;
}
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan