我正在使用Swift 2.0 Xcode 7.0並在我的應用程序中使用Core Data。 我在從coredata取回結果時面臨麻煩。 我的實體名稱是用戶它是NSManagedObject的子類。當我從編輯器創建的NSManagedObject子類時,Xcode 7創建了兩個班,我從[Entity]投射到無關類型實體在CoreData中始終失敗
- User.swift
- 擴展類用戶+ CoreDataProperties.swift
我User.swift類
import Foundation
import CoreData
class User: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
用戶+ CoreDataProperties.swift類 進口基金會 進口CoreData
extension User {
@NSManaged var facebookId: String?
@NSManaged var googleId: String?
@NSManaged var userAge: NSNumber?
@NSManaged var userEmail: String?
@NSManaged var userId: NSNumber?
}
現在我設法成功地保存記錄。現在,當我取回它時,我正在使用下面的代碼。我基於用戶名
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
//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
我看到這個鏈接,隨後取出一條記錄。但這裏沒有更新用做
http://www.sthoughts.com/2015/06/09/swift-2-0-snippet-coredata-fetching-with-error-handling/
請幫我分揀了這一點。任何幫助將不勝感激。
讓用戶= fetchResults [0]給出錯誤..不能下標類型[用戶]? –
@RajanMaheshwari:請注意,我將您的代碼更改爲強制案例'as! [用戶]'。我已經給答案添加了一個解釋。 –
是的,你是對的馬丁。這些?和!總是讓我困惑。你能否給我提供一些可以向我澄清這些事情的教程(!和?)。您的解決方案奏效接受.. –