gpt4 book ai didi

ios - 将 NSManagedObject 转换为子类返回 nil

转载 作者:行者123 更新时间:2023-11-28 07:12:23 25 4
gpt4 key购买 nike

当我在 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 ,以防有帮助。

最佳答案

这个日志输出

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 自动生成类文件)。

关于ios - 将 NSManagedObject 转换为子类返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27947585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com