0

嗨,我正在尝试修复 SugarRecord,这是使用 CoreData 和 iCloud 的好方法。

我使用以下方法在上面遇到此错误:

 public func find(finder: SugarRecordFinder) -> SugarRecordResults
    {

        let fetchRequest: NSFetchRequest = SugarRecordCDContext.fetchRequest(fromFinder: finder)



        var objects = [NSManagedObject]()
        do{
              objects = try self.contextCD.executeFetchRequest(fetchRequest) as! [NSManagedObject]

        }
        catch
        {

        }
        if objects == nil  {
            objects = [NSManagedObject]()
        }

        return SugarRecordResults(results: SugarRecordArray(array: objects), finder: finder)
    }

错误在线 -if objects == nil {

虽然在网上搜索后我找不到解决这个问题的方法。如果你能帮忙,谢谢。

4

1 回答 1

1

executeFetchRequest总是返回一个数组。如果什么都找不到,则数组为空。

只需删除

if objects == nil  {
   objects = [NSManagedObject]()
}

更好的语法是

public func find(finder: SugarRecordFinder) -> SugarRecordResults
{

  let fetchRequest: NSFetchRequest = SugarRecordCDContext.fetchRequest(fromFinder: finder)
  do {
    let objects = try self.contextCD.executeFetchRequest(fetchRequest) as! [NSManagedObject]
    return SugarRecordResults(results: SugarRecordArray(array: objects), finder: finder)
  }
  catch let error as NSError {
    // do error handling
    return SugarRecordResults()
  }
}
于 2015-11-06T09:22:11.313 回答