以动态方式对NSMutableArray元素求和

时间:2014-06-09 20:28:45

标签: ios objective-c nsmutablearray

我有一个NSMutableArray,格式为:(< -x->是我放在这里的分隔符,以便于执行交易总和)

23,00 <-x-> 20/09/2019 12:43:23 PM
89,00 <-x-> 20/09/2019 12:43:23 PM
13,00 <-x-> 20/09/2019 12:43:23 PM

53,00 <-x-> 22/10/2019 21:09:05 AM

93,00 <-x-> 23/10/2019 12:12:45 PM
83,00 <-x-> 23/10/2019 12:12:45 PM

正如你所看到的,我的阵列有价格和日期时间,所有这一切都是,找到一种方法来获得当天等于的所有字段并总结所有的价格值,并把完整的总和在具有日期时间的其他数组中,例如:

125,00  <-x-> 20/09/2019 12:43:23 PM // 23 + 89 + 13 = 125,00 + date time that are equals
53,00   <-x-> 22/10/2019 21:09:05 AM // 53 only but not have another value with the same date time
176,00     <-x-> 23/10/2019 12:12:45 PM // 93 + 83 = 176,00 + date time that are equals

好吧,我没有尝试任何事情,因为我不知道从哪里开始,所以我在这里请你们帮我解决这个难题,我将非常感激。

感谢。

4 个答案:

答案 0 :(得分:1)

每当您发现自己需要像<-x->这样的分隔符时,就应该使用比字符串更好的数据结构了。这可以是字典或自定义对象 在这两种情况下,您都可以使用KVC集合运算符@sum

NSNumber *totalPrice = [dates valueForKeyPath:@"@sum.price"];

我编写了一个示例代码,其中我使用了一个包装器类,它以您的格式获取字符串并创建一个包装器对象来保存价格和日期,如NSNumber和NSDate。

#import <Foundation/Foundation.h>


@interface Wrapper : NSObject
@property (nonatomic, strong) NSNumber *price;
@property (nonatomic, strong) NSDate *date;

-(id)initWithString:(NSString *) string;
@end

@implementation Wrapper

-(id)initWithString:(NSString *) string
{
    if(self = [super init]){
        [self processString:string];
    }
    return self;
}

-(void)processString:(NSString *)string
{
    NSArray *array = [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsSeparatedByString:@" <-x-> "];

    static NSNumberFormatter *nf;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        nf = [[NSNumberFormatter alloc] init];
        nf.decimalSeparator = @",";
    });

    NSNumber *n = [nf numberFromString:array[0]];
    self.price = n;

    static NSDateFormatter *df;
    static dispatch_once_t dfOnceToken;
    dispatch_once(&dfOnceToken, ^{
        df = [[NSDateFormatter alloc] init];
        df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
        df.dateFormat = @"dd/MM/yyyy hh:mm:ss a";
    });
    NSDate *d = [df dateFromString:array[1]];
    self.date = d;

}

@end



int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSArray *strings = @[
                             @"23,00 <-x-> 20/09/2019 12:43:23 PM",
                             @"89,00 <-x-> 20/09/2019 12:43:23 PM",
                             @"13,00 <-x-> 20/09/2019 12:43:23 PM"
                             ];
        NSMutableArray *objects = [@[] mutableCopy];

        for (NSString *string in strings) {
            [objects addObject:[[Wrapper alloc] initWithString:string]];
        }

        NSNumber *totalPrice = [objects valueForKeyPath:@"@sum.price"];
        NSLog(@"%@", totalPrice);

    }
    return 0;
}

输出:125

答案 1 :(得分:0)

我不想给你确切的代码,但这就是你如何做到它的胆量:

NSString *string = @"83,00 <-x-> 23/10/2019 12:12:45 PM";

//We first want to split the string based on the ' <-x-> ', we could just use NSString's substringWithRange but if the leading numberical values are ever larger than 4 digits it would break. So in order to keep it flexible we split it in half.
NSArray *subStrings = [string componentsSeparatedByString:@" <-x-> "];
NSLog(@"%@", subStrings);


//When we seperate the first value in subStrings will be "23,00"
NSString *numericalValues = subStrings[0];
NSLog(@"numbericalValues: `%@`", numericalValues);


//We get the date out of the subString compoenents NSString's substringWithRange since the date string will always be the same length.
NSString *trimmedDateString = [subStrings[1] substringWithRange:NSMakeRange(0, 10)];
NSLog(@"trimmedDateSTring: `%@`", trimmedDateString);


/*
 So now we have turned this:

 23,00 <-x-> 20/09/2019 12:43:23 PM

 into this: 

 23,00
 20/09/2019


 You can use this same logic in a loop to compare date's and convert the 23,00 into a value you can add.
*/

答案 2 :(得分:0)

概括地说,您希望解析字符串的组成部分,按日期对元素进行分组,并在每个组中添加日期。字典是一种很好的方法。在伪代码中:

NSDictionary results

for string in array:
  date = split(" <-x-> ", string)[0]
  priceString = split(" <-x-> ", string)[1]
  price = split(",", pricesString)[0]
  results[date] = results[date] or 0
  results[date] += price

答案 3 :(得分:-1)

我努力尝试,最后我得到了答案,我创建了下面的代码,它完全符合我的预期,谢谢大家帮助我!

  #import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSMutableArray * array01 = [NSMutableArray arrayWithObjects:@"23,00 <-x-> 20/09/2019 12:43:23 PM",@"89,00 <-x-> 20/09/2019 12:43:23 PM",@"13,00 <-x-> 20/09/2019 12:43:23 PM",@"53,00 <-x-> 22/10/2019 21:09:05 AM",@"53,00 <-x-> 22/10/2019 21:09:05 AM",@"93,00 <-x-> 23/10/2019 12:12:45 PM",@"83,00 <-x-> 23/10/2019 12:12:45 PM",@"83,00 <-x-> 23/10/2019 12:12:45 PM",@"83,00 <-x-> 23/10/2019 1:12:45 PM",@"23,00 <-x-> 20/09/2019 12:43:23 PM",@"23,00 <-x-> 20/09/2019 12:43:23 PM",nil];

        NSMutableArray * array02 = [[NSMutableArray alloc] init];

        NSLog(@"%@",array01);

        int index2 = 0;

        for(int x=0;x<[array01 count];x++){


            if([array02 count] == 0){

                [array02 addObject:array01[x]];

            }else{

                NSMutableArray *lstaInfo02;

                if([array02 count] == index2){
                    //Array count menor que index 2 isso quer dizer que -> Passamos para uma data diferente

                    NSLog(@"Apos esta linha apareçera um erro! array02 contagem -> %d index2 contagem -> %d",array02.count,index2);

                    index2 = index2 - 1;

                }

                lstaInfo02 = [[array02[index2] componentsSeparatedByString:@"<-x->"] mutableCopy];

                NSMutableArray *lstaInfo01 = [[array01[x] componentsSeparatedByString:@"<-x->"] mutableCopy];

                NSString *string1 = lstaInfo02[1];
                NSString *string2 = lstaInfo01[1];


                if([string1 isEqualToString:string2]){

                    NSString *objects = [NSString stringWithFormat:@"%.2f <-x->%@",[lstaInfo02[0] floatValue] + [lstaInfo01[0] floatValue], string2];

                    NSLog(@"SUM -> %@ + %@ = %@",lstaInfo01[0],lstaInfo02[0],objects);

                    [array02 replaceObjectAtIndex:index2 withObject:objects];

                    NSLog(@"%@",array02);

                    if([array02 count] > 1){

                    index2++;

                    }

                }else{
                    [array02 addObject:array01[x]];

                    //O problema se encontra aqui quando vai fazer o ++

                    index2++;

                }


            }

        }


                    NSLog(@"%@",array02);
    }
    return 0;
}