将NSManagedObject存储在数组

时间:2016-07-14 02:55:01

标签: ios arrays swift nsmanagedobject

我正在努力弄清楚如何最好地解决我的问题。我目前有一个表格视图,其中包含用户可以选择并上传或“移至垃圾箱”(另一个表视图)的单元格。问题是,当我将NSManagedObject存储在swift数组中以了解它们已被选中时,swift会复制,因为数组是值类型。

    var selectedInspections = [Inspection]()

有没有办法解决这个问题,同时保持类型安全(我知道我可以使用NSArray,但是因为类型安全而不愿意)。我也不想使用表格视图编辑模式。

    if let indexPath = tableView.indexPathForRowAtPoint(sender.center) {
        if let inspection = inspectionFetcher.objectAtIndexPath(indexPath) as? Inspection {
            inspection.selected = sender.checked

            if inspection.selected {
                selectedInspections.append(inspection)
            }
            else {
                if let index = selectedInspections.indexOf(inspection) {
                    selectedInspections.removeAtIndex(index)
                }
            }

            // Disable the action button if there are no inspections selected
            actionButton.enabled = selectedInspections.count > 0 ? true : false
        }
    }

enter image description here

核心数据初始化

    guard let modelURL = NSBundle.mainBundle().URLForResource("Inspection", withExtension:"momd") else {
        fatalError("Error loading model from bundle")
    }

    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else {
        fatalError("Error initializing mom from: \(modelURL)")
    }

    let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)

    managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = psc
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        let docURL = urls[urls.endIndex-1]
        /* The directory the application uses to store the Core Data store file.
         This code uses a file named "DataModel.sqlite" in the application's documents directory.
         */
        let storeURL = docURL.URLByAppendingPathComponent("Inspection.sqlite")
        do {
            try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
        } catch {
            fatalError("Error migrating store: \(error)")
        }
    }

然后我这样做是为了更新我的实体上的属性然后保存它

        // Move all the selected inspections to the trash
        for inspection in self.selectedInspections {
            inspection.inTrash = true
        }

        // Save
        try! self.managedObjectContext.save()

        try! self.inspectionFetcher.performFetch()

        // Empty the selected inspections array
        self.selectedInspections.removeAll()

0 个答案:

没有答案