iphone - 相互比较数组元素,在重复项上将某个属性加在一起?

标签 iphone ios objective-c nsmutablearray

我试图遍历我的数组并根据数组中对象的名称属性查找重复的对象。找到重复项后,我需要组合这些对象,名称和单位值保持不变,我只想将数量值加在一起。此时我想删除两个重复项并将新对象添加到数组中。

如果很难删除两个对象并添加另一个对象(可能会弄乱索引?),那么可以将新对象添加到过滤后的数组中,只要没有发现重复项也被添加到该数组中。所以新数组将包含我以前的所有值,重复值按数量组合。

到目前为止我有这个:

NSMutableSet* existingNames = [NSMutableSet set];
NSMutableArray* filteredArray = [NSMutableArray array];

for (id object in ingredientsArray)
{
    if (![existingNames containsObject:[object name]])
    {
        [existingNames addObject:[object name]];
        NSLog(@"%@", @"DUPLICATE FOUND");

        //create new object to store the new info in.
        ingredient *info = [[ingredient alloc] initWithname:[object name] quantity:[/* How do I add the quanitity values of the two objects that are duplicates here? */] unit:[object unit]];

        //add this to filtered array.
        [filteredArray addObject:object];

        //remove object from array.
        [ingredientsArray removeObject:object];
    }
}

谢谢

最佳答案

您不能修改正在枚举的数组。编译器应该提示这个,如果不是,它应该在运行时崩溃。

我认为您代码中的逻辑有些困惑。 if 子句检查字符串是否包含在您的重复项数组中 - 因此“DUPLICATE FOUND”肯定不是真的。

在这种情况下,只遍历 id 是不好的做法。如果您可以更强烈地键入您的对象,那就更好了。还建议遵守诸如 Capitalized 类名之类的约定。

减少迭代次数的一个技巧是只迭代唯一名称。 NSSet 有一个技巧可以实现这一点:

NSArray *names = [ingredientsList valueForKeyPath:@"name"];
NSSet *uniqueNames = [NSSet setWithArray:names];
NSArray *resultArray = [NSMutableArray array];
NSPredicate *nameFilter;

for (NSString *ingredientName in uniqueNames) {
   predicate = [NSPredicate predicateWithFormat:@"name = %@", ingredientName];
   NSArray *entries = [ingredientsList filteredArrayUsingPredicate:predicate];
   Ingredient *ingredient = entries[0];
   if (entries.count > 1) {
      NSLog(@"Found %d instances of %@.", entries.count, ingredientName);
      NSNumber *sum = [entries valueForKeyPath:@"@sum.quantity"];
      ingredient.quantity = sum;
   }
   [resultsArray addObject:ingredient];
}

这里假设 Ingredient 类至少有两个属性,name (NSString) 和 quantity (NSNumber)。这也适用于普通的 NSDictionaries。

关于iphone - 相互比较数组元素,在重复项上将某个属性加在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18686813/

相关文章:

iphone - 在 FlipSide 上带有导航 Controller 和表格 View 的实用程序

javascript - iOS PWA - 打开 map 返回到空白屏幕

ios - 有没有办法使用 SwiftUI 将可选对象绑定(bind)到 Toggle/Slider

iphone - 无法在 NSManagedObject 类 'ClassName' 上调用指定的初始值设定项

objective-c - 尝试关闭键盘时出现 "unrecognized selector"错误

iphone - 将对象返回给 ViewController 中的方法

javascript - 将 NSDate 传递给 iOS 中的本地 UIWebView - Objective C

iphone - 获取永久 ID 后,核心数据无法为对象完成故障

iphone - 多次下载文件而不锁定 ios 中的 UI

iphone - 为我的设备构建时,如何选择 Xcode 4 将使用哪个构建配置?