【发布时间】:2015-03-11 02:40:38
【问题描述】:
我有这个问题。我正在用 Swift 开发应用程序并使用 RestKit 来检索数据并将其发布回 API。但是我遇到了路障。如果检索到的 JSON 有效负载包含一些 null 值,应用程序将崩溃并显示以下消息:
*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[NSNull 长度]:无法识别的选择器发送到实例 0x1994faba0”
我该怎么办? 映射的属性是字符串。
映射对象:
public class User: NSObject {
public var id: Int? = 0
public var email: String?
public var firstName: String?
public var lastName: String?
public var name: String?
public var office: String?
public var phone: String?
public var company: String?
}
映射:
let userMapping = RKObjectMapping(forClass: User.self)
userMapping.addAttributeMappingsFromDictionary([
"id": "id",
"email": "email",
"first_name": "firstName",
"last_name": "lastName",
"name": "name",
"company": "company",
"phone": "phone",
"office": "office",
])
let responseDescriptor = RKResponseDescriptor(mapping: userMapping, pathPattern: currentUserPath, keyPath: "data", statusCodes: NSIndexSet(index: 200))
objectManager.addResponseDescriptor(responseDescriptor)
JSON 响应:
{
"status": "ok",
"data": {
"id": 1,
"email": "some@email.com",
"created_at": 1418832714451,
"updated_at": 1421077902126,
"admin": true,
"first_name": "John",
"last_name": "Doe",
"company": null,
"office": null,
"phone": null,
"name": "John Doe"
}
}
它会在以下各项中崩溃:办公室、电话和姓名。
【问题讨论】:
-
显示 JSON 和您的映射。改进 JSON。将 NSNull 处理添加到您的代码中。
-
我已经编辑了我的问题以满足您的要求 :) 如何使用 RestKit 自己处理 NSNull?
-
你使用的是什么版本(它应该转换为 nil 真的)
-
RestKit 0.24.0,Xcode 6.1.1,iOS 8.1
-
如果我从映射中删除公司、办公室和电话,它就可以正常工作。