gpt4 book ai didi

swift - 与服务器同步核心数据 - 多次添加相同的对象

转载 作者:行者123 更新时间:2023-11-30 13:33:49 24 4
gpt4 key购买 nike

我有一个用户可以选择的类别列表。由于我计划添加新类别而不必发送新更新,因此我想在每次用户启动应用程序时从我的服务器加载新类别。我想出了这段代码,但每次运行时它都会不断添加相同的类别。

 func loadDealCategory(){

let myUrl = NSURL(string: "\(ipAddress)/v1.0/dealCategory.php")
let request = NSMutableURLRequest(URL: myUrl!)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{ data, response, error in

if error != nil {

print("error\(error)")

}else{


do{

let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray


let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext

for jsonDictionary in json {

// listing of columns in JSON seed file
let categoryDescription = jsonDictionary.valueForKey("category_description") as! String

print(categoryDescription)

let newCategory = NSEntityDescription.insertNewObjectForEntityForName("Categories", inManagedObjectContext: managedContext)
newCategory.setValue(categoryDescription, forKey: "category_description")

// I tried also format: "category_description = %@"


let fetchRequest = NSFetchRequest(entityName: "Categories")
fetchRequest.predicate = NSPredicate(format: "category_description LIKE %@", categoryDescription)

do {
let fetchResults = try managedContext.executeFetchRequest(fetchRequest)

print(fetchResults)

if fetchResults.count == 0{

do {
try managedContext.save()
//5
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}


}else{

print("\(categoryDescription) already exist!")



}


} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}


}


} catch{

print("something went wrong loading json")


}

}
}
task.resume()
}
  • 可以吗,将其加载到 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  • 最佳答案

    发现问题,我在检查对象是否已经在实体中之前插入了该对象。

      if fetchResults.count == 0{

    let newCategory = NSEntityDescription.insertNewObjectForEntityForName("Categories", inManagedObjectContext: managedContext)
    newCategory.setValue(categoryDescription, forKey: "category_description")


    }else{

    print("Could not save \(error), \(error.userInfo)")

    }

    然后才保存

     do {
    try managedContext.save()

    } catch let error as NSError {

    print("Could not save \(error), \(error.userInfo)")
    }

    关于swift - 与服务器同步核心数据 - 多次添加相同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36309578/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com