Swift 3 核心数据
Posted
技术标签:
【中文标题】Swift 3 核心数据【英文标题】:Swift 3 Core Data 【发布时间】:2016-09-15 17:41:15 【问题描述】:尝试在 Swift 3 中执行 NSFetchRequest 时出现以下错误
Generic parameter 'ResultType' could not be inferred
我检查了很多链接,但我无法弄清楚如何解决它。
这就是我正在做的事情
ViewController.swift
func loadData()
let request = NSFetchRequest(entityName: "Grocery") //Error occurs here(Generic parameter 'ResultType' could not be inferred)
do
let results = try manageObjectContext.execute(request)
groceries = results as! [NSManagedObject]
tableView.reloadData()
catch
fatalError("Error is retriving Gorcery items")
【问题讨论】:
Swift 4 中 CoreData 的快速介绍:medium.com/swift2go/… 【参考方案1】:试试这个:
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Grocery")
它应该工作:)
因此您的代码应如下所示:
func loadData()
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Grocery")
do
let results = try manageObjectContext.execute(request)
groceries = results as! [NSManagedObject]
tableView.reloadData()
catch
fatalError("Error is retriving Gorcery items")
【讨论】:
谢谢,它有效,但是我将其更改为使用 NSManagedObject 子类【参考方案2】:致谢:Nitesh Patil https://medium.com/@imnitpa/swift-3-core-data-7b00b50f5782
import UIKit
import CoreData
class ViewController: UIViewController
override func viewDidLoad()
super.viewDidLoad()
view.backgroundColor = .white
let appDelegate = UIApplication.shared.delegate as!AppDelegate
let context = appDelegate.persistentContainer.viewContext
//adding new user and saving in database...
let newUser = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)
newUser.setValue("Batman", forKey: "username")
newUser.setValue("Robin", forKey: "password")
do
try context.save()
print("saved")
catch
print("Error occured...")
// restoring data back from database
let request = NSFetchRequest < NSFetchRequestResult > (entityName: "Users")
request.returnsObjectsAsFaults = false
do
let results =
try context.fetch(request)
if results.count > 0
for result in results as![NSManagedObject]
if let username = result.value(forKey: "username") as ? String
print(username)
else
print("No results")
catch
print("Couldn't fetch results")
【讨论】:
【参考方案3】:你也可以用这个:
let request : NSFetchRequest<Grocery> = Grocery.fetchRequest()
当你执行请求时,你会得到 [Grocery] 类型的结果:
let results : [Grocery] = try manageObjectContext.execute(request)
或
let results = try manageObjectContext.execute(request)
【讨论】:
以上是关于Swift 3 核心数据的主要内容,如果未能解决你的问题,请参考以下文章