当我在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 = "[email protected]";
    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 = "[email protected]";
    userId = "9e99451d-ef9d-4876-bfd3-4a987c2fe316";
})

显示即使该实体是NSManagedObject,该类实际上也是SCUser。这很可能是因为您尚未在模型中设置类名,并且大概是手动生成了SCUser类代码文件?您需要设置类名称(最好使用Xcode或mogenerator自动生成类文件)。

09-25 20:01