ios - 你如何在 Swift 中从 NSManagedObject 获取 NSSet?

标签 ios swift core-data nsset

对于在我的核心数据中建模的基本 Flashcard 应用程序,我有从 SetCard 的一对多关系。

每个 Set 都有一个集合名称、集合描述和许多 card1 的关系。每张 Card1 都有正面、背面和照片。在我的 TableView 中,我设法从核心数据中检索所有已保存的 Set 并显示它们。现在我想在用户单击我的下一个 View Controller 中的相应单元格时获取每个 Set 的卡片。

这是我的 TableView Controller 代码:

// MARK: Properties
var finalArray = [NSManagedObject]()

override func viewDidLoad() {
    getAllSets()
    println(finalArray.count)
}

func getAllSets() {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!
    let fetchRequest = NSFetchRequest(entityName:"Set")
    var error: NSError?
    let fetchedResults = managedContext.executeFetchRequest(fetchRequest,error: &error) as? [NSManagedObject]
    println("Am in the getCardSets()")
    if let results = fetchedResults {
        finalArray = results
        println(finalArray.count)
    }
    else {
        println("Could not fetch \(error), \(error!.userInfo)")
    }
}

// MARK: Displaying the data

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
     return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return finalArray.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SetTableViewCell

    let sets = finalArray[indexPath.row]

    cell.setName.text = sets.valueForKey("setName")as? String
    cell.setDescription.text = sets.valueForKey("setDescription")as? String
    return cell
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "ShowDetail" {
        let dest = segue.destinationViewController as! Display

        // Get the cell that generated this segue.
        if let selectedCell = sender as? SetTableViewCell {
            let indexPath = tableView.indexPathForCell(selectedCell)!

            let selectedSet = finalArray[indexPath.row]
            dest.recievedSet = selectedSet
        }
    }
}

在我的目标 View Controller 中,我将如何检索 recievedSet 中的所有卡片?我尝试将 NSSet 转换为数组并将其转换为 [Card1] 数组,但是当我尝试将第一个 Card1 的 front String 属性显示到标签上时,应用程序崩溃,出现错误

CoreData: error: Failed to call designated initializer on NSManagedObject class 'NSManagedObject' 
fatal error: Array index out of range

这是我的详细 View Controller 代码。

@IBOutlet weak var front: UILabel!

var finalArray = [Card1]()
finalArray = retrievedSet.allObjects as![Card1]
front.text = finalArray[0].front

最佳答案

为您的细节 Controller 提供 CardSet 类型的属性(我使用“CardSet”,因为“Set”是 Swift 内置类型名称)。您将所选集传递给此 Controller 。

您可以使用一个属性来排序,或者使用 allObjects 生成一个没有特定顺序的数组。

var cardArray = [Card1]()
var cardSet: CardSet?

viewDidLoad() {
   super.viewDidLoad()
   if let validSet = cardSet {
     cardArray = validSet.cards.allObjects as! [Card1]
   }
}

您的代码无法正常工作,因为 finalArray[CardSet] 类型,所以 finalArray[indexPath.row] 类型>CardSet 不可转换为 NSSet 类型。相反,与 Card1relationship 是您要查找的 NSSet

最后,我建议给细节 Controller 一个 NSFetchedResultsController,有一个属性来排序,并在获取的结果 Controller 的谓词中使用传递的 CardSet

关于ios - 你如何在 Swift 中从 NSManagedObject 获取 NSSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32673134/

相关文章:

iphone - 核心数据迁移 "can' t 将模型与名为 'foo' 的两个不同实体合并”

ios - 如何调试重载篮板?

ios - 如果位置更改或不使用 AFN 3,如何定期向服务器发送后台位置?

android - 当设备处于 sleep 状态时对敲击电话执行操作?

ios - 用 UIBezierPath 表示 CIRectangleFeature - Swift

ios - 使用 Magical Record 获取记录时如何获取 "Newest Record"

ios - 为什么要调整此 UISearchBar 的大小?

objective-c - 如何在 objective-c 中创建 BOOL 实例变量?

swift - AlamoFire(异步)调用中的 UIProgressView 进度更新非常慢

ios - 使用核心数据从文本字段中保存和检索数据