将 NSManagedObject 转换为子类返回 nil
Posted
技术标签:
【中文标题】将 NSManagedObject 转换为子类返回 nil【英文标题】:Casting NSManagedObject to subclass returns nil 【发布时间】:2015-01-14 16:18:35 【问题描述】:当我在 Swift 中使用 RestKit 0.23.0 时尝试将 NSManagedObject 强制转换为我的模型类 (SCUser) 时,返回值为 nil。操作如下:
var urlString:String = SCApi.sharedInstance.apiUrl + "users/find_or_create?name=\(name)&email=\(email)"
var url = NSURL(string: urlString)!
var request = NSURLRequest(URL: url)
var responseDescriptor = RKResponseDescriptor(mapping: SCUser.entityMapping(), method: RKRequestMethod.Any, pathPattern: nil, keyPath: "user", statusCodes: nil)
var operation = RKManagedObjectRequestOperation(request: request, responseDescriptors: [responseDescriptor])
operation.managedObjectContext = RKManagedObjectStore.defaultStore().mainQueueManagedObjectContext
operation.managedObjectCache = RKManagedObjectStore.defaultStore().managedObjectCache
operation.setCompletionBlockWithSuccess(
(operation:RKObjectRequestOperation!, result:RKMappingResult!) -> Void in
println("result: \(result.firstObject())")
var object:NSManagedObject = result.firstObject() as NSManagedObject
if let user = (object as? SCUser)
println("success: \(user)")
else
println("failure")
,
failure:
(operation:RKObjectRequestOperation!, error:NSError!) -> Void in
println("error: \(error)")
)
operation.start()
当它运行时,它表明result.firstObject()
是一个 SCUser,但不会将其转换为一个:
result: <NSManagedObject: 0x1740aee20> (entity: SCUser; id: 0xd000000000140000 <x-coredata://7CFB18B0-0E2D-4190-B8DF-20470425CFE3/SCUser/p5> ; data:
authenticationToken = Dt7tjbLtUzSAgBdzCyC3;
name = g;
email = "foo@gmail.com";
userId = "9e99451d-ef9d-4876-bfd3-4a987c2fe316";
)
failure
我已将 SCUser 类和 RestKit 初始化 here 放入,以防万一。
【问题讨论】:
【参考方案1】:这个日志输出
result: <NSManagedObject: 0x1740aee20> (entity: SCUser; id: 0xd000000000140000 <x-coredata://7CFB18B0-0E2D-4190-B8DF-20470425CFE3/SCUser/p5> ; data:
authenticationToken = Dt7tjbLtUzSAgBdzCyC3;
name = g;
email = "foo@gmail.com";
userId = "9e99451d-ef9d-4876-bfd3-4a987c2fe316";
)
显示该类实际上是NSManagedObject
,即使实体是SCUser
。这很可能是因为您没有在模型中设置类名,并且大概是您手动生成了SCUser
类代码文件?您需要设置类名(最好使用 Xcode 或 mogenerator 自动生成类文件)。
【讨论】:
以上是关于将 NSManagedObject 转换为子类返回 nil的主要内容,如果未能解决你的问题,请参考以下文章
如何将 NSObject 模型类转换为 NSManagedObject 的子类?
如何使用 RKValueTransformer 将 NSString 转换为 Core Data NSManagedObject
如何将 NSManagedObject 的 NSKeyedUnarchive 子类导入核心数据?
无法将“NSManagedObject”类型的返回表达式转换为“字符串”类型?