我对iOS更新鲜。在我的应用程序中,我有3个可变数组,其中包含像
这样的对象NSMutableArray *MuteItem = [NSMutableArray alloc]initWithObjects:@"a", @"b", @"b", @"c", @"c", @"c", nil]];
NSMutableArray *MuteQuantity = [NSMutableArray alloc]initWithObjects:@"1", @"1", @"1", @"1", @"1", @"1", nil]];
NSMutableArray *MutePrice = [NSMutableArray alloc]initWithObjects:@"4", @"3", @"3", @"6", @"6", @"6", nil]];
现在我需要打印3个可变数组值并计算相同项目的数量并计算价格也像对象
MuteItem = { a, b, c }
MuteQuantity = { 1, 2, 3 } // counting of same item's quantity like {1, 1+1, 1+1+1}
MutePrice = { 4, 6, 18 } // here addition of same item's prices like {4, 3+3, 6+6+6}
所以任何人,请你帮我解决这个问题。提前谢谢。
答案 0 :(得分:1)
此代码将完全按照您的要求执行,甚至可以处理MuteItem中的任何键,并将生成三个新数组,其中包含来自三个原始数组中每个数据的聚合信息。
NSMutableArray* muteItem = [[NSMutableArray alloc] initWithObjects: @"a", @"b", @"b", @"c", @"c", @"c", nil];
NSMutableArray* muteQuantity = [[NSMutableArray alloc] initWithObjects: @"1", @"1", @"1", @"1", @"1", @"1", nil];
NSMutableArray* mutePrice = [[NSMutableArray alloc] initWithObjects: @"4", @"3", @"3", @"6", @"6", @"6", nil];
NSMutableArray* setItem = [NSMutableArray array];
NSMutableArray* setQuantity = [NSMutableArray array];
NSMutableArray* setPrice = [NSMutableArray array];
NSSet* itemSet = [NSSet setWithArray: muteItem];
for (NSString* key in itemSet) {
NSIndexSet* indices = [muteItem indexesOfObjectsPassingTest: ^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [obj isEqualToString: key];
}];
__block NSInteger totalQuantity = 0;
__block NSInteger totalPrice = 0;
[indices enumerateIndexesUsingBlock: ^void(NSUInteger idx, BOOL *stop) {
totalQuantity += [[muteQuantity objectAtIndex: idx] integerValue];
totalPrice += [[mutePrice objectAtIndex: idx] integerValue];
}];
[setItem addObject: key];
[setQuantity addObject: [NSNumber numberWithInteger: totalQuantity]];
[setPrice addObject: [NSNumber numberWithInteger: totalPrice]];
}
注意:此代码假定您使用的是ARC。另外,在原始代码中,您忘记nil
终止数组构造函数。
totalPrice
的定义更改为float
,并且您希望将totalPrice +=
行的结尾从integerValue
更改为floatValue
。
EDIT2:重命名以大写字母开头的所有变量,因为这违反了标准命名约定。只有类名称应以大写字母开头,变量应始终以小写字母开头,或者以_
为实例变量。 :)