Reputation: 14571
I am using Swift 2.0 Xcode 7.0 and using Core Data in my app. I am facing trouble in fetching the results back from coredata. My entity name is User which is a subclass of NSManagedObject. When I created the NSManagedObject Subclass from editor, XCode 7 created two classes for me
My User.swift class
import Foundation
import CoreData
class User: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
User+CoreDataProperties.swift class import Foundation import CoreData
extension User {
@NSManaged var facebookId: String?
@NSManaged var googleId: String?
@NSManaged var userAge: NSNumber?
@NSManaged var userEmail: String?
@NSManaged var userId: NSNumber?
}
Now I managed to successfully save a record. Now when I am fetching it back I am using the following code. I am fetching a single record based on 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
//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
I saw this link and followed. But here no updation is done
http://www.sthoughts.com/2015/06/09/swift-2-0-snippet-coredata-fetching-with-error-handling/
Please help me in sorting this out. Any help will be appreciated.
Upvotes: 0
Views: 4291
Reputation: 540005
The fetch request returns an array of objects (which can have zero, one, or more elements), even if you expect only a single result. In your case, you would simply access the first element of the result array:
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 ...
}
Alternatively:
if let user = fetchResults.first {
user.age = 24
// ...
} else {
// no matching user found ...
}
Also note that you know that the fetched objects have the type User
(because you configured the entities class in the Core Data model
inspector), therefore a forced cast as! [User]
is appropriate here.
Upvotes: 3
Reputation: 6515
The problem is that you mix User
and [User]
. The first one is a user-object, and it has a userAge
property. The second one is a list of users and it doesn't have a userAge
property. E.g. if a list users
has two elements, then users[0]
and users[1]
were users, but users
itself is just a list of users
Upvotes: 1