在Swift上遇到泛型的奇怪问题
具有NSManagedObject
子类层次结构,其扩展名为:
BaseCloudKitItem< -MyObject
extension BaseCloudKitItem {
func updateDataWithCKRecord(record: CKRecord!, inManagedObjectContext context: NSManagedObjectContext!) {
cloudKitRecordID = record?.recordID.recordName
cloudKitType = record?.recordType
println("\(self) updateDataWithCKRecord:inManagedObjectContext: called")
}
}
extension MyObject {
override func updateDataWithCKRecord(record: CKRecord!, inManagedObjectContext context: NSManagedObjectContext!) {
super.updateDataWithCKRecord(record, inManagedObjectContext: context)
title = record?.objectForKey("title") as? NSString
}
}
有一个通用类:
class CloudFetcher<T : BaseCloudKitItem> {
class func someFetchingAndMappingMethod(completion:(() -> Void)?) {
someFetchingMethodWithCompletion { (records, error) in
if let err = error {
completion?(nil, err)
} else {
NSManagedObjectContext.saveDataInBackgroundWithBlock({ (localContext) in
T.deleteAllInContext(localContext)
for record in records {
let object = T.createEntityInContext(localContext) as T
object.updateDataWithCKRecord(record, inManagedObjectContext: localContext)
}
}, completion: completion)
}
}
}
}
和用法:
CloudFetcher<MyObject>.someFetchingAndMappingMethod { _ in
}
将类传递给通用 CloudFetcher
MyObject
所以问题是我发现从基类 BaseCloudKitItem
调用泛型内部的方法,而不是来自 MyObject
。
如果我将CloudFetcher接口声明从class CloudFetcher<T : BaseCloudKitItem>
更改为class CloudFetcher<T : MyObject>
,它的工作原理很完美,但没有必要以这种方式使用泛型。
此外,在目标方法内的println()
日志中,我可以看到所需的类,但仍然没有调用所需的方法:
<MyObject: 0x7aab7130> (entity: MyObject; id: 0x802f5bf0 <x-coredata:///InstrumentToken/t1AAF2438-9DF7-44DA-89B2-C3C1BE3D91FE17> ; data: {
cloudKitRecordID = "fb4fac88-40e5-4aef-af3c-6e36867dbf5f";
cloudKitType = MyObject;
title = nil;
}) updateDataWithCKRecord:inManagedObjectContext: called
多数民众赞成对我来说很奇怪,也许有人可以提供我,我可以解决它?
谢谢!