-1

我在数据库中有一些消息,我每次都会从该用户的服务器获取全部消息。我必须比较两个数组并且需要过滤新消息。每条消息都有一个唯一的 id,即 messageId

NSMutableArray *arrayMessagesServer = [response objectForKey:@"messageList"];
    arrayMessagesDB=[[NSMutableArray alloc]initWithArray:[self getMessagesFromDB]];



    for (int i = 0; i<[arrayMessagesServer count]; i++)
    {

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"messageId == %i", [[arrayMessagesServer objectAtIndex:i] integerValue]];


        //If message not exists, saving message to DB
        if(![arrayMessagesDB filteredArrayUsingPredicate:predicate])
        {
            NSDictionary *dict = [arrayForMessagesInServer objectAtIndex:i];

            Messages *objMessages = [NSEntityDescription insertNewObjectForEntityForName:@"Messages" inManagedObjectContext:context];
            [objMessages setValue:[dict objectForKey:@"message"] forKey:@"messageBody"];
            [objMessages setValue:[dict objectForKey:@"messageId"] forKey:@"messageId"];
            [objMessages setValue:[NSString stringWithFormat:@"%@",[dict objectForKey:@"messageType"]] forKey:@"messageType"];
        }

    }

    NSError *error1;
    if (![context save:&error1])
    {
        NSLog(@"Problem saving: %@", [error1 localizedDescription]);
    }
4

1 回答 1

2

如果我理解正确,您需要将消息列表与服务器同步,并仅将新的且尚不存在于数据库中的消息插入数据库。

您可以使用 IN 语句。如下所示:

NSMutableArray *arrayMessagesServer = [response objectForKey:@"messageList"];
arrayMessagesDB = [[NSMutableArray alloc]initWithArray:[self getMessagesFromDB]];

// this gives you an array of identifiers (NSString? as in your model): 
NSArray *existingIdentifiers = [arrayMessagesDB valueForKey:@"messageId"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"messageId NOT IN %@", existingIdentifiers];
NSArray *newMessages = [arrayMessagesServer filteredArrayUsingPredicate:predicate];

快速简单!

于 2013-10-20T19:04:00.253 回答