我希望我的应用程序在后台将所有服务器信息加载到Core Data实体。我创建了一个名为' Event'然后在其中创建了5个属性。另外,我为我的实体创建了NSManagedObject子类:
import Foundation
import CoreData
@objc(Event)
class Event: NSManagedObject {
@NSManaged var category: String
@NSManaged var date: String
@NSManaged var event: String
@NSManaged var location: String
@NSManaged var time: String
}
以下是我如何加载所有数据并希望将其插入核心数据实体:
func loadAllData(){
println("loading all data")
let params = ServerConstants.infoParam + "=true"
// creating request, set its method to POST and append params to request
var request = NSMutableURLRequest(URL: NSURL(string: ServerConstants.getInfoURL)!)
request.HTTPMethod = "POST"
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
// start loading data in background
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in
if error == nil {
let json = JSON(data: data)
self.defaults.setObject(json["lastCategoriesId"].string, forKey: "lastCategoriesId")
self.defaults.setObject(json["lastEventsId"].string, forKey: "lastEventsId")
//println(json)
var maxValue = Float(json["categories"].count + json["events"].count)
println("maxself. - \(maxValue)")
var error: NSError?
var array = json["events"]
let newItem = NSEntityDescription.insertNewObjectForEntityForName("Event", inManagedObjectContext: self.managedObjectContext!) as! Event
for var i: Int = 0; i < array.count; i++ {
newItem.category = array[i]["category"].string!
newItem.event = array[i]["event"].string!
newItem.location = array[i]["location"].string!
newItem.date = array[i]["date"].string!
newItem.time = array[i]["time"].string!
println(i)
}
if !self.managedObjectContext!.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
println("done")
}
}
task.resume()
}
}
问题是我的for循环工作非常慢。一次迭代约1秒。我究竟做错了什么?数据大约是3500行。
这是我的json:
{
"lastEventsId" : "3602",
"events" : [
{
"date" : "lorem",
"time" : "ipsum",
"event" : "dolor",
"category" : "sit",
"location" : "amet"
},...
}
我试着为循环运行:
for var i: Int = 0; i < array.count; i++ {
println(i)
}
再次进行1次迭代1秒钟。但是,如果我只将索引最大长度设置为3500,则将整个循环迭代约1秒。
for var i: Int = 0; i < 3500; i++ {
println(i)
}
答案 0 :(得分:0)
let limit = array.count;
for i in 0..<limit {
//do your stuff
}