I ran into a really simple CoreData issue but it seems hard to solve. Writing a simple chat app where every user has many messages.
class CoreUser: NSManagedObject
{
@NSManaged var firstname: String?
@NSManaged var id: String?
@NSManaged var lastname: String?
@NSManaged var nickname: String?
@NSManaged var messages: NSSet
}
class CoreMessage: NSManagedObject
{
@NSManaged var body: String?
@NSManaged var owner: CoreUser
@NSManaged var state: String
@NSManaged var timestamp: NSDate
}
The relationship is: one-to-many
Fetching user entity:
func getCoreUser(userId: String) -> CoreUser?
{
var error: NSError?;
let fetchRequest = NSFetchRequest(entityName: "CoreUser");
let nodeId = NSString(string: userId.lowercaseString);
let pred = NSPredicate(format: "id == %@", nodeId);
fetchRequest.fetchLimit = 1;
fetchRequest.predicate = pred;
let fetchResults = self.managedObjectContext!.executeFetchRequest(fetchRequest, error: &error) as? [CoreUser];
if let results = fetchResults
{
return results.first;
}
return nil;
}
How can I limit the related message entity (20 messages, sorted by date). The result array contains all the messages from this user.
Thx for helping.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…