我正在构建一个应用程序,当服务器连接不再可用时将位置存储在核心数据中,然后在连接恢复时将这些位置推送到服务器。
从核心数据中获取并打印这些获取的对象后,我最初会遇到大量错误。我了解故障及其代表的含义,但故障数不应该是相同数量的对象吗?错误的数量大大超过了对象的数量(我可以打印出 100 多个错误,仅针对 {longitude, latitude, timestamp} 的 10 个 Location 实体数组对象)。
我希望有人能告诉我我做错了什么,或者这是否是通常的行为。非常感激。
当服务器返回连接时,AppDelegate.swift 调用 fetch 并打印核心数据对象
var fetchedCoreData = self.coreDataManagement.fetchLog()
for dataPoints in fetchedCoreData
{
println(dataPoints)
}
`CoreDataManager.swift 处理存储/获取位置实体的核心数据
var locations = [NSManagedObject]()
//coordinates passed from AppDelegate
func saveCoords(latCoord: String, longCoord: String, timeCoord: String) {
let appDelegate =
UIApplication.sharedApplication().delegate as AppDelegate
let managedContext = appDelegate.managedObjectContext!
let entity = NSEntityDescription.entityForName("Location",
inManagedObjectContext:
managedContext)
let coordsInfo = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext:managedContext)
coordsInfo.setValue(latCoord, forKey: "latitude")
coordsInfo.setValue(longCoord, forKey: "longitude")
coordsInfo.setValue(timeCoord, forKey: "timestamp")
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
locations.append(coordsInfo)
}
`
//fetch core data objects
func fetchLog() -> Array<AnyObject> {
let appDelegate =
UIApplication.sharedApplication().delegate as AppDelegate
let fetchRequest = NSFetchRequest(entityName: "Location")
fetchRequest.returnsObjectsAsFaults = false;
var fetchResults = appDelegate.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil)
return fetchResults! as Array<AnyObject>
}
`