我正在将字典中的JSON解析为核心数据模型。当我创建一个NSFetchRequest来查找模型中的现有条目时,我得到一个例外。
AppDelegate类:
for dictionary : AnyObject in airports as AnyObject[] {
let name : NSString? = dictionary.valueForKey("name") as? NSString
if name {
var airport = Airport.fromDictionary(dictionary as NSDictionary, context: managedObjectContext)
}
}
var managedObjectContext: NSManagedObjectContext {
if !_managedObjectContext {
let coordinator = self.persistentStoreCoordinator
if coordinator != nil {
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
型号:
class func fromDictionary(dictionary: NSDictionary, context: NSManagedObjectContext) -> Airport! {
let id = dictionary["code"] as NSString
var airport : Airport = airportWithCode(id, context: context)
return airport
}
class func airportWithCode(code: String, context: NSManagedObjectContext) -> Airport! {
var fetchRequest = NSFetchRequest()
let entityDescription = NSEntityDescription.entityForName(Airport.entityName(), inManagedObjectContext: context)
^.... Exception point
fetchRequest.entity = entityDescription
fetchRequest.predicate = NSPredicate(format: "code ==[c] %@", code)
var error: NSError?
let results: NSArray = context.executeFetchRequest(fetchRequest, error: &error)
var result = results.firstObject as Airport
if result != nil {
return result as Airport
} else {
var airport = createWithCode(code, context: context) as Airport
return airport
}
}