将 NSManagedObject 转换为子类 returns nil

Casting NSManagedObject to subclass returns nil

当我在 Swift 中使用 RestKit 0.23.0 时尝试将 NSManagedObject 转换为我的模型 class (SCUser),return 值为 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 class 和 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";
})

表明 class 实际上是 NSManagedObject,即使实体是 SCUser。这很可能是因为您没有在您的模型中设置 class 名称,并且您可能已经手动生成了 SCUser class 代码文件?您需要设置 class 名称(最好使用 Xcode 或 mogenerator 自动生成 class 文件)。