【问题标题】:Loading the results set for Core Data fetch request加载 Core Data 获取请求的结果集
【发布时间】:2018-08-18 19:14:34
【问题描述】:

我有一个这样声明的变量:

private var theText = String()
private var aId = String()

然后我执行一个获取请求并希望将其加载到该变量中:

    let predicateA = NSPredicate(format: "active == %@", true as CVarArg);
    let predicateB = NSPredicate(format: "theId == %@", aId);
    let andPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: [predicateA, predicateB]);

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext;
    let requestData = NSFetchRequest<NSFetchRequestResult>(entityName: "DataTable");
    requestData.predicate = andPredicate;

    do
    {
        let results = try context.fetch(requestData);          

        dataactivitiesid = results.first

        // let resultset = results as! [NSManagedObject];

        /* for data in results
         {
         // let testyId: Any? = (data as AnyObject).value(forKey: "testyId");
         } */
    }
    catch
    {
        print("Error in fetching data");
    }

我是否需要像上面注释的代码那样循环遍历结果集,或者因为我知道它只返回一行,我可以使用 .first 吗?提前致谢。

【问题讨论】:

    标签: ios iphone swift core-data swift3


    【解决方案1】:

    如果您只期望一个项目,则不需要循环。

    我建议可选地将first 的结果绑定到一个变量,如果没有找到条目,该变量可以是nil

    而且您不需要复合谓词,单个谓词可以包含与同一对象相关的多个条件。 最后,这不是 Objective-C,去掉后面的分号。

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext;
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "DataTable")
    let predicate = NSPredicate(format: "active == TRUE AND theId == %@", aId)
    fetchRequest.predicate = predicate
    
    do {
        if let result = try context.fetch(fetchRequest).first  {      
            dataactivitiesid = result
        }
    
    } catch {
        print(error) // print the actual error not a meaningless literal string
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 2011-12-18
      • 2014-08-17
      • 1970-01-01
      • 2023-01-02
      • 1970-01-01
      • 2012-02-27
      相关资源
      最近更新 更多