从CoreData

时间:2016-04-12 12:52:21

标签: ios swift core-data

  1. 我想从CoreData中删除自定义单元格中UILabel提供的单个字符串。所以从tableview中删除一行是行不通的。

  2. 另外,我想检查特定字符串是否在CoreData值中。

  3. 例如:

    我有一个名为“Favorites”的实体,其名为“services”的属性带有我插入的名为“micro”的字符串。我想删除“微”。另外,我想检查“微”(例如)是否来自属性“services”和实体“Favorites”的字符串。

    我试过这个:

    1

    let serString = servico.text
    
            let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let contexto:NSManagedObjectContext = appDel.managedObjectContext
    
            let entidade = NSEntityDescription.entityForName("Favorites", inManagedObjectContext: contexto)
            let pedido = NSFetchRequest(entityName: "Favorites")
            pedido.predicate = NSPredicate(format: "service = %@", serString!)
            let p:Favorites? = Favorites(entity: entidade!, insertIntoManagedObjectContext: contexto)
                contexto.deleteObject(p!)
    

    ...但它没有删除字符串“serString”

    2。 试过这个:

    var request : NSFetchRequest = NSFetchRequest(entityName: "Favorites");
        request.predicate = NSPredicate(format: "services = %s", "micro")
        let results : [NSManagedObject] = context.executeFetchRequest(request, error: &error)
        if (results.count > 0) {
            print("exists")        }
        else {
            //Doesn't exist
        }
    

    ...但是在“& error”中出现错误,说“使用未解析的标识符'错误'”

    图2(b)。

    也尝试了这个,但崩溃了输出提供的应用

    “打印错误说明: (NSError)错误=“超出范围”

    (lldb)“

    let request : NSFetchRequest = NSFetchRequest(entityName:     "Favorites");
        request.predicate = NSPredicate(format: "services = %s", "micro")
    do {
    let results : [NSManagedObject] = try   context.executeFetchRequest(request) as! [Favorites]
    if (results.count > 0) {
                print("exists")        }
            else {
                //Doesn't exist
            }
            // success ...
        } catch let error as NSError {
            // failure
            print("Fetch failed: \(error.localizedDescription)")
        }
    

    更新

    1. 此代码最终用于删除字符串:

      let favoriteFetchRequest = NSFetchRequest(entityName:"Favorites")
          let predicate = NSPredicate(format: "services = %@", serv)
          favoriteFetchRequest.predicate = predicate
      do {
         let fetchedEntities = try       context.executeFetchRequest(favoriteFetchRequest) as! [NSManagedObject]
      
      for entity in fetchedEntities {
      context.deleteObject(entity)
      try context.save()
      }
      } catch let error as NSError {
      print("Fetch failed: \(error.localizedDescription)")
      }
      
    2. 有关2的任何帮助吗?

1 个答案:

答案 0 :(得分:0)

1。我认为你需要这样的东西:

str = ""s + c;