【问题标题】:Swift: CoreData call to specific object IDSwift:CoreData 调用特定对象 ID
【发布时间】:2016-09-23 07:33:47
【问题描述】:

作为一名新开发人员,我正在发现新概念,我一直在尝试理解核心数据,但在我浏览的教程中遇到了问题。使用对象 ID 调用项目时出现错误。错误是 - Type 'Person.Type' 没有下标成员。 这可能是因为我没有正确执行此操作,或其他原因。我相信有人可以对这个主题有所启发

这是我编写的一个函数,用于从数据堆栈中获取特定项目,

func getObjectById(id: NSManagedObjectID) -> Person?{
    return context.objectWithID(id) as? Person
}

这是我调用函数的方式

func callFirstObject(){
    let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    let personService = PersonService(context: context)

    let firstPerson = personService.getObjectById(Person[0].objectID!)
}

从那里我只是在一个按钮内调用callFirstObject()

编辑:我有一个函数可以调用我的所有对象

func getAllObjects() -> [Person]{
    return getObject(withPredicate: NSPredicate(value: true))
}

还有一个用谓词调用我所有对象的函数

func getObject(withPredicate queryPredicate: NSPredicate) -> [Person]{
    let fetchRequest = NSFetchRequest(entityName: Person.entityName)

    fetchRequest.predicate = queryPredicate
    do {
        let response = try context.executeFetchRequest(fetchRequest)
        print("\(response)")
        return response as! [Person]
    } catch let error as NSError {
        // In case of failure
        print("There was an error - \(error)")
        return [Person]()

    }
}

我只是想调用堆栈中的特定名称。

如果需要更多信息,我很乐意提供。

【问题讨论】:

    标签: ios swift cocoa-touch core-data


    【解决方案1】:

    Person 没有下标成员,因为 Person 是类名。应在 Person 对象数组上调用下标 [0]

    可能看起来像这样:

    func callFirstObject(){
        let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
        let personService = PersonService(context: context)
        // Person Array
        let persons: [Person] = [person1, person2, person3 ]
    
        let firstPerson = personService.getObjectById(persons[0].objectID!)
    }
    

    编辑:虽然我对逻辑有点困惑。如果您已经拥有该人,则必须访问 objectID,那么我不明白您为什么需要再次获取它。我们能看到更多关于这两种方法的上下文吗?

    从下面的评论中回答您的问题:

    如果您想获取 Person 模型的所有记录,您可以执行以下操作:

    let appDelegate =
      UIApplication.sharedApplication().delegate as! AppDelegate
    
    let managedContext = appDelegate.managedObjectContext
    
    let fetchRequest = NSFetchRequest(entityName: "Person")
    
    do {
      let results =
      try managedContext.executeFetchRequest(fetchRequest)
      people = results as! [NSManagedObject]
    } catch let error as NSError {
      print("Could not fetch \(error)")
    }
    

    这将为您提供存储在 Core Data 中的所有 Person 对象

    【讨论】:

    • 这是您正确的类名,但我的 .xcdatamodeld 中的实体称为 Person,有什么方法可以将其作为数组调用吗?或者它不是那样工作的?有没有办法可以将数据模型作为一个整体称为数组?还是我必须用一定数量的对象制作一个数组
    • @GabrielMSC 见我上面的编辑。该 sn-p 将检索所有 Person 对象作为一个数组。
    • @GabrielMSC 刚刚看到你编辑。我很清楚,你在这里的最终目标是什么?你到底想达到什么目的?
    • 基本上我只是在搞乱 CRUD,我希望能够添加名称,显示我添加到列表中的名称,编辑这些名称,然后从列表中删除它们。
    猜你喜欢
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多