ios - 从 [Entity] 转换为无关类型的 Entity 在 CoreData 中总是失败

标签 ios swift core-data swift2

我正在使用 Swift 2.0 Xcode 7.0 并在我的应用程序中使用 Core Data。 我在从 coredata 取回结果时遇到了麻烦。 我的实体名称是 User,它是 NSManagedObject 的子类。当我从编辑器创建 NSManagedObject 子类时,XCode 7 为我创建了两个类

  1. User.swift
  2. 扩展类User+CoreDataProperties.swift

我的User.swift

import Foundation
import CoreData

class User: NSManagedObject {

// Insert code here to add functionality to your managed object subclass

}

User+CoreDataProperties.swift 类 导入基金会 导入核心数据

extension User {
@NSManaged var facebookId: String?
@NSManaged var googleId: String?
@NSManaged var userAge: NSNumber?
@NSManaged var userEmail: String?
@NSManaged var userId: NSNumber?
}

现在我成功保存了一条记录。现在,当我取回它时,我正在使用以下代码。我正在根据 UserID 获取单个记录

let fetchRequest = NSFetchRequest(entityName: "User")
fetchRequest.predicate = NSPredicate(format: "userId == %d",userId )

do {
     let fetchResults = try
     self.managedObjectContext.executeFetchRequest(fetchRequest) as? [User]

     // At this line I am getting warning 
     // Cast from [User] to unrelated type User always fails
     var userObj = fetchResults as! User

enter image description here

//How to get rid of the warning

//So how to fetch back and make changes in the object. I want to updates the change. For ex I want to do something like
     userObj.userAge = 30 //and then update this and save the context

    } 
     catch let fetchError as NSError {
    print("error: \(fetchError.localizedDescription)")
   }
    // if I use this line
    let user = fetchResults as [User]?
    // It does cast but then I am unable to find any of the members like userId, userAge in it. It says value of type [User]? has no member userAge

enter image description here

我看到了这个链接并关注了。但是这里没有更新

http://www.sthoughts.com/2015/06/09/swift-2-0-snippet-coredata-fetching-with-error-handling/

请帮我解决这个问题。任何帮助将不胜感激。

最佳答案

获取请求返回对象的数组(可以有 零个、一个或多个元素),即使您只期望一个 结果。在您的情况下,您只需访问第一个元素 结果数组的:

let fetchResults = try
 self.managedObjectContext.executeFetchRequest(fetchRequest) as! [User]
if fetchResults.count > 0 {
    let user = fetchResults[0] //  `User`
    user.age = 24
    // ...
} else {
    // no matching user found ...
}

或者:

if let user = fetchResults.first {
    user.age = 24
    // ...
} else {
    // no matching user found ...
}

另请注意,您知道获取的对象具有User 类型 (因为您在 Core Data 模型中配置了实体类 检查员),因此强制转换 as! [User] 在这里是合适的。

关于ios - 从 [Entity] 转换为无关类型的 Entity 在 CoreData 中总是失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32921299/

相关文章:

swift - 使用 NSPredicate 对 TableView 中的核心数据进行排序(Swift)

iphone - 以编程方式在 Objective-C 中创建属性?

ios - 适用于 iOS 7.1 的 SKShapeNode 和 swift

iOS PHImageManager.default().requestImage 回调被同一张图片调用两次

ios - 如何使 Storyboard中的 UILabel 和 UIButton 大写

iphone - 保存后 UITableViewCell 和 Coredata 上的 UIImage 的方向发生变化

iphone - 两个应用程序(iPhone 和 iPad)之间的核心数据 iCloud 同步

ios - Swift:如何查找 Realm 数据库包含自定义字符串

ios - 我应该如何在 xcode Storyboard中链接 View Controller ?

ios - 类没有初始化器 Swift