【问题标题】:Fetch Request Error获取请求错误
【发布时间】:2017-05-16 18:17:23
【问题描述】:

我已将上一个故事板中的用户输入名称保存到实体“UserInfo”下的 xcdatamodel 中,名称为“name”。我试图在下一个故事板中获取它以显示在标签中以问候用户。我收到错误“无法调用类型为 'NSFetchRequet' 的初始化程序,其参数类型为 '(entityName:String, attributeName: String)”

     guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
     return
     }

     //getting the managed context where the entity we need is
     let managedContext = appDelegate.persistentContainer.viewContext

     //make fetch request
     let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "UserInfo", attributeName: "name")


     //try to fetch the entity we need, else print error
     do {
     Username = try managedContext.fetch(fetchRequest)
     } catch let error as NSError {
     print("Could not fetch. \(error), \(error.userInfo)")
     }

【问题讨论】:

    标签: swift core-data fetch nsfetchrequest


    【解决方案1】:

    NSFetchRequest 没有采用参数attributeName: 的初始化程序,就像错误所说的那样。您的选项是NSFetchRequest(entityName:)NSFetchRequest()

    如有疑问,请在 API 参考中查找该类,以确保您了解如何使用它。

    【讨论】:

      【解决方案2】:

      NSFetchRequest 没有初始化器entityName:attributeName,你必须使用

       let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "UserInfo")
      

      fetch 总是返回一个数组。如果实体中只有一条记录,则获取第一项和属性name的值:

       do {
           let users = try managedContext.fetch(fetchRequest)
           if let user = users.first {
               Username = user.value(forKey: "name")
           }
       } catch let error as NSError {
           print("Could not fetch. \(error), \(error.userInfo)")
       }
      

      如果有多个记录,您可以应用谓词。


      不要guardAppDelegate。如果这个类不存在,应用程序甚至不会启动。感叹号是safe as safe can

      let appDelegate = UIApplication.shared.delegate as! AppDelegate
      

      【讨论】:

        猜你喜欢
        • 2021-08-08
        • 2016-07-10
        • 2017-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多