2016-06-30 16 views
1

我的問題很簡單: 在我自己的Swift類中遵守NSMutableCopying協議的最佳方式是什麼(可能有一些代碼解釋)?符合Swift中的NSMutableCopying?

class CustomClass: NSObject, NSMutableCopying { 
    var string1: String 
    var string2: String 

    required override init() { 
     self.string1 = "string1" 
     self.string2 = "string2" 
    } 

    // MARK: NSMutableCopying ?? 

} 

回答

0

在Objc,我使用:

+ (instancetype)allocWithZone:(struct _NSZone *)zone OBJC_SWIFT_UNAVAILABLE("use object initializers instead"); 

但是在斯威夫特這種方法不可用。

所以我實現這樣的:

class CustomClass: NSObject, NSMutableCopying { 
    var string1: String 
    var string2: String 

    required override init() { 
     self.string1 = "string1" 
     self.string2 = "string2" 
    } 

    func mutableCopyWithZone(zone: NSZone) -> AnyObject { 
     let customObject = CustomClass() 
     customObject.string1 = string1 
     customObject.string2 = string2 
     return customObject 
    } 
} 

我不知道是否正確與否,但我想不出更好的辦法。

持續關注..