Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

ios - CoreData limit related entities batch size

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

But what you can do instead is fetch the CoreMessage objects related to 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 retrieved messages:

fetchRequest.fetchLimit = 20

together with a suitable sort descriptor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...