swift - 无法将类型 '__NSCFSet' (0x109b56408) 的值转换为 'NSArray' Swift 4

标签 swift core-data

我正在尝试从 notification.userInfo 中获取一组位置对象,插入和删除值并相应地更新 map 注释。它不允许我将其转换为 [Location] 类型。

出现以下错误

Could not cast value of type '__NSCFSet' (0x109b56408) to 'NSArray'

var managedObjectContext: NSManagedObjectContext! {
    didSet {
        NotificationCenter.default.addObserver(forName: Notification.Name.NSManagedObjectContextObjectsDidChange, object: managedObjectContext, queue: OperationQueue.main) { (notification) in
            if self.isViewLoaded {
                if let dictionary = notification.userInfo {
                    print(dictionary["inserted"])

                    if let inserted = dictionary["inserted"]{
                        var location = [Location]()
                        location = inserted as! [Location]
                    }

                    if let deleted = dictionary["deleted"] {
                    }
                }
            }
        }
    }
}

最佳答案

数据不是数组,是集合。并使用适当的 key 访问数据。

var managedObjectContext: NSManagedObjectContext! {
    didSet {
        NotificationCenter.default.addObserver(forName: Notification.Name.NSManagedObjectContextObjectsDidChange, object: managedObjectContext, queue: OperationQueue.main) { (notification) in
            if self.isViewLoaded {
                if let dictionary = notification.userInfo {
                    print(dictionary[NSInsertedObjectsKey])

                    if let inserted = dictionary[NSInsertedObjectsKey] as? Set<Location> {
                        var location = Array(inserted)
                    }

                    if let deleted = dictionary[NSDeletedObjectsKey] {
                    }
                }
            }
        }
    }
}

关于swift - 无法将类型 '__NSCFSet' (0x109b56408) 的值转换为 'NSArray' Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53327347/

相关文章:

ios - 我可以从后台线程调用或运行 Core Data Main Context (viewContext) 吗?

ios - Xcode UI 测试 - 向测试类添加测试

ios - 从 Parse 加载图像文件时出现错误

iOS 将电话号码转换为国际格式

ios - NSPredicate 不返回任何获取请求的结果,适用于数组过滤

ios - 核心数据和私有(private)框架

ios - 核心数据 : Insert and delete with To many relationship

file - 在 Swift 中,如何将现有二进制文件读入数组?

ios - 更改 map 中心后标注在错误位置打开

ios - 如果由于网络连接不良而尚未完成创建,如何删除 CKRecord?