Fabrizio
Fabrizio

Reputation: 183

Extract all the data from Array and do the sum?

I have added some data into a myMutableArray:

- (void)calculate {

    DataObject* pObj = [DataObject objStart:(dataStart) 
                                     objEnd:(dataEnd) 
                                     objDay:(day)];

    [self.myMutableArray addObject:pObj];
}

I need to extract then only day (int) and sum all the values. I was thinking at something like that, but i'm missing how to extract only day ...

  for(id *tObj in self.myMutableArray) {
    // day = day + day
 }

DataObject is implemented here:

   @implementation DataObject

+ (id)objStart:(NSDate*)objStart objEnd:(NSDate*)objEnd objDay:(int)objDay {

DataObject *dataObject = [[self alloc] init];
dataObject.objStart = objStart;
dataObject.objEnd = objEnd;
dataObject.objDay = objDay;
return dataObject;
}
@end

Upvotes: 0

Views: 212

Answers (2)

Sandeep
Sandeep

Reputation: 21144

There is one elegant and really nice solution that cocoa provides with key value coding. You could take a look at http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/KeyValueCoding/Articles/CollectionOperators.html for more detail.

I dont really understand about your model but I will suppose my own model to provide you the solution, hope you find it interesting.

Say I have a model named Data as follows;

@interface Data:NSObject
  @property(nonatomic, strong) NSString *name;
  @property(nonatomic) int day;
@end
@implementation Data
  @synthesize name, day;
@end

Now, in your some classes you create instances of data object and add it to an array.

NSMutableArray *myArray = [NSMutableArray array];
Data *data =[ [Data alloc] init];
data.name = @"First Name";
data.day = 10;
[myArray addObject:data];
data = [[Data alloc] init];
data.name = @"Second Name";
data.day = 20;
[myArray addObject:data];

Now, with this array you can play kvc game.

[myArray valueForKey:@"name"]

gives a new array as;

(First Name, Last Name)

[myArray valueForKey:@"day"] gives;

(10, 20 )

And for sum of all the days, you would just do,

[myArray valueForKeyPath:@"@sum.day"] and that would provide you with 30.

That's it. Hope I understood your question well. ;)

Upvotes: 1

Anoop Vaidya
Anoop Vaidya

Reputation: 46543

Do you want this ? (I have to make a lot of self-assumptions)

NSUInteger totalDay;
for(id tObj in self.myMutableArray) {
    // day = day + day
  totalDay+=tObj.objDay;
}

Upvotes: 1

Related Questions