问题描述
我遇到了一个非常简单的CoreData问题,但似乎很难解决。编写一个简单的聊天应用程序,每个用户都有很多消息。
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
}
关系是:一对多
获取用户实体:
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;
}
如何限制相关消息实体(20条消息,按日期排序) 。结果数组包含该用户的所有消息。
How can I limit the related message entity (20 messages, sorted by date). The result array contains all the messages from this user.
Thx提供帮助。
推荐答案
提取请求始终从托管对象上下文返回对象。您无法获取已修改的对象,例如 CoreUser
对象与 CoreMessage
具有受限关系。
A fetch request always returns the objects from the managed object context. You cannot fetch "modified" objects, e.g. CoreUser
objects with a "restricted" relationship to CoreMessage
.
但是您可以做的是取与给定用户的与
相关的 CoreMessage
对象:
But what you can do instead is fetch the CoreMessage
objects relatedto the given user:
let fetchRequest = NSFetchRequest(entityName: "CoreMessage")
fetchRequest.predicate = NSPredicate(format: "owner.id == %@", nodeId)
现在,您可以添加抓取限制以限制检索到的
消息的数量:
and now you can add a fetch limit to restrict the number of retrievedmessages:
fetchRequest.fetchLimit = 20
连同合适的排序描述符。
together with a suitable sort descriptor.
这篇关于CoreData限制相关实体的批次大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!