0

我有两个NSMutableArrays。一个数组包含来自数据库的记录,另一个数组包含来自 Web 服务的记录。

我想使用唯一键(如barcodeID. 另外,如果barcodeID密钥相同,那么我想从数组中删除该项目。这就像我正在更新我的数据库记录。如果我们从 web 服务获得相同的记录,那么我不想插入它们。

请帮助我,我无法打破这个逻辑。

4

3 回答 3

5

if Product.barcodeID uniquely identifies your objects, then you can use that member to implement -[Product hash] and -[Product isEqual:].

then you can easily use Product in NSSets. NSSet and NSMutableSet contain several methods to combine and remove sets.

于 2012-08-21T19:51:27.290 回答
0

The brute force method of doing such comparison is for every record in one array is checked with every record in another. If you find it then stop and discard the object. if you do not find it, then you add it to the array. This of course will have a very high time complexity with a worse case scenario is O(n^2). you could shorten this down by using certain data structures inside your database and web service. Maybe storing them in sorted order or through some algorithm.

You should do some research yourself before asking this question. I shall leave you the option to find a way to optimize your code.

Good luck!

于 2012-08-21T19:51:03.723 回答
0

这是蛮力方法的一种想法。如上所述,与替代方案相比,这非常慢。

- (void)myUpdateFunction
{
    NSMutableArray *baseDatabaseArray;
    NSMutableArray *baseWebServiceArray;

    for (int i = 0; i < baseWebServiceArray.count; i++) {
        id value = [[baseWebServiceArray objectAtIndex:i] valueForKey:@"barcodeID"];
        NSArray *array = [baseDatabaseArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"barcodeID = %@", value]];
        if (array.count > 0)
        {
            id obj = [array objectAtIndex:0];
            [baseDatabaseArray removeObject:obj];
        }
        [baseDatabaseArray addObject:[baseWebServiceArray objectAtIndex:i]];
    }
}

我一直在使用Magical Record并且喜欢它。不过,您必须为此使用 Core Data。这是我的更新代码在 Magical Record 中的样子。

- (void)updateDatabase
{
    Class class = NSClassFromString(self.managedObjectClassName);

    if ([class MR_countOfEntities] > 0) {
        for (NSArray *array in self.totalBatches) {
            [class MR_updateFromArray:array];
        }
    } else {
        for (NSArray *array in self.totalBatches) {
            [class MR_importFromArray:array];
        }
    }

    [self.totalBatches removeAllObjects];
}

如果您对 Core Data 的感觉有任何疑问,或者如果您需要我了解算法,请随时提问。

于 2012-08-21T20:11:01.167 回答