我在应用程序中使用CoreData。我创建了一个具有两个属性的实体。一种是Int类型,第二种是可转换类型。我能够成功保存我的记录。但是,当我尝试获取时,它会崩溃。还有一件事,无需使用Transformable类型,一切都可以正常工作。可能是什么原因?那是可变形的类型吗?如果是,那么解决方案是什么?

func saveUserInfoInDatabase(userDetails: FleetInfoDetails) {
    self.deleteUserInfoFromDatabase()
    let entityDescription = NSEntityDescription.entityForName("UserInfo", inManagedObjectContext: self.userInfoObjectContext)
    let data = UserInfo(entity: entityDescription!, insertIntoManagedObjectContext: self.userInfoObjectContext)
    print(userDetails)
    data.info = userDetails
    data.sync = 1
    do {
        try self.userInfoObjectContext.save()
    } catch {
        fatalError("Failure to save context: \(error)")
    }
}

func deleteUserInfoFromDatabase() {
    let fetchRequest = NSFetchRequest(entityName: "UserInfo")
    if #available(iOS 9.0, *) {
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            try DatabaseManager.sharedInstance.persistentStoreCoordinator.executeRequest(deleteRequest, withContext: self.userInfoObjectContext)
            do {
                try self.userInfoObjectContext.save()
            } catch {
                let saveError = error as NSError
                print(saveError)
            }
        } catch let error as NSError {
            let saveError = error as NSError
            print(saveError)
        }
    } else {
        // Fallback on earlier versions
    }
}

func fetchUserInfoFromDatabase(){
    let request = NSFetchRequest(entityName: "UserInfo")
    do {
        let results = try self.userInfoObjectContext.executeFetchRequest(request) as? [UserInfo] //Getting crash here
        if results!.count > 0 {

        }else{
            print("0 results or potential error")
        }
    } catch {
        let saveError = error as NSError
        print(saveError)
    }
}


我将以下对象类分配给Transformable attirbute。

class FleetInfoDetails: NSObject {

var fleetId: Int!
var fleetImage: String!
var accessToken: String!
var email: String!
var phone: String!
var password: String!
var name: String!
var teams: Array<AssignedTeamDetails>?

func encodeWithCoder(_aCoder: NSCoder) {   }
func initWithCoder(aCode:NSCoder) {

}

init(json: NSDictionary) {

    if let fleetId = json["fleet_id"] as? Int {
        self.fleetId = fleetId
    }
    if let fleetImage = json["fleet_image"] as? String {
        if fleetImage.isEmpty{
            self.fleetImage = nil
        }
        self.fleetImage = fleetImage
    }
    if let accessToken = json["access_token"] as? String {
        if accessToken.isEmpty{
            self.accessToken = nil
        }
        self.accessToken = accessToken
    }
    if let email = json["email"] as? String {
        if email.isEmpty{
            self.email = nil
        }
        self.email = email
    }

    if let phone = json["phone"] as? String {
        if phone.isEmpty{
            self.phone = nil
        }
        self.phone = phone
    }
    if let password = json["password"] as? String {
        if password.isEmpty{
            self.password = nil
        }
        self.password = password
    }

    if let name = json["name"] as? String {
        if name.isEmpty{
            self.name = nil
        }
        self.name = name
    }

    if let items = json["teams"] as? NSArray{
        if items.count == 0{
            teams = [AssignedTeamDetails]()
        } else {
            teams = [AssignedTeamDetails]()
        }
        for item in items{
            if let team = AssignedTeamDetails(json: item as! NSDictionary) as AssignedTeamDetails! {
                teams?.append(team)
            }
        }
    }
 }

最佳答案

我只是拼搏,最终实现了它。这是我的解决方案:

class FleetInfoDetails: NSObject, NSCoding {

var fleetId: Int!
var accessToken: String!

required init(coder aDecoder: NSCoder) {
    fleetId = aDecoder.decodeObjectForKey("fleetId") as! Int
    accessToken = aDecoder.decodeObjectForKey("accessToken") as! String
}

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(fleetId, forKey: "fleetId")
    aCoder.encodeObject(accessToken, forKey: "accessToken")
}

init(json: NSDictionary) {

if let fleetId = json["fleet_id"] as? Int {
    self.fleetId = fleetId
}
if let accessToken = json["access_token"] as? String {
    if accessToken.isEmpty{
        self.accessToken = nil
    }
    self.accessToken = accessToken
}
}
}


我刚刚在对象类中添加了NSCoding。然后实现所需的init()和encodeWithCode()方法。之后,我使用NSKeyedArchiver和NSKeyedUnarchiver保存和获取数据。

func saveUserInfoInDatabase(userDetails: FleetInfoDetails) {
    self.deleteUserInfoFromDatabase()
    let entityDescription = NSEntityDescription.entityForName("UserInfo", inManagedObjectContext: self.userInfoObjectContext)
    let data = UserInfo(entity: entityDescription!, insertIntoManagedObjectContext: self.userInfoObjectContext)
    data.info = NSKeyedArchiver.archivedDataWithRootObject(userDetails)
    data.sync = 1
    do {
       try self.userInfoObjectContext.save()
    } catch {
       fatalError("Failure to save context: \(error)")
    }
}

func fetchUserInfoFromDatabase(){
    let request = NSFetchRequest(entityName: "UserInfo")
    do {
      let results = try    self.userInfoObjectContext.executeFetchRequest(request) as? [UserInfo]

    if results!.count > 0 {
       let userData = NSData(data: results?.first?.valueForKey("info") as! NSData)
       let userDetails = NSKeyedUnarchiver.unarchiveObjectWithData(userData) as! FleetInfoDetails

    }else{
        print("0 results or potential error")
    }
} catch {
    let saveError = error as NSError
    print(saveError)
}
}


希望它能帮助任何人。如果还有其他解决方案,请告诉我。

关于ios - 在Swift 2.0中FetchRequest崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37253812/

10-17 02:43