Eric
Eric

Reputation: 21

Returning total value of object property from array

I am trying to get the total value totalPurchaseSum of an property stockPurchasePrice from all objects in an array arrPurchaseActions.

This are the properties (user.h):

@property (nonatomic, strong) NSMutableArray *arrPurchaseActions;

@property (nonatomic) CGFloat totalSumPurchased;

-(CGFloat)totalSumPurchased:(CGFloat)stockPurchasePrice;

This is the method I am trying to use (User.m):

-(CGFloat)totalSumPurchased:(CGFloat)stockPurchasePrice
{
    CGFloat totalSumPurchased = 0;
    size_t count = [self.arrPurchaseActions count];
    for (int i = 0; i < count; i++) {
            totalSumPurchased = totalSumPurchased +        [[self.arrPurchaseActions[i].stockPurchasePrice];
}

    return totalSumPurchased;
}

Can anybody help me to get this working?

Upvotes: 0

Views: 150

Answers (2)

rmaddy
rmaddy

Reputation: 318774

This line:

totalSumPurchased = totalSumPurchased + [[self.arrPurchaseActions[i].stockPurchasePrice];

needs to be:

totalSumPurchased = totalSumPurchased + [[self.arrPurchaseActions[i] stockPurchasePrice];

You can't use the property accessor with objects of type id (which is what NSArray objectAtIndex: returns). Instead, call the getter method for the property.

Upvotes: 0

mspensieri
mspensieri

Reputation: 3521

Try this:

NSNumber * sum = [self.arrPurchaseActions valueForKeyPath:@"@sum.stockPurchasePrice"];

Upvotes: 2

Related Questions