Adding up NSNumber's formatted as Currency

Discussion in 'iOS Programming' started by gijibo, Oct 18, 2010.

  1. gijibo macrumors newbie

    Joined:
    Jun 13, 2010
    #1
    Hi,

    I've been trying desperately to find how to do this.

    I have a series of products stored in a dictionary (which comes from a plist), each product as a "Price" key, and a number as its value. Using NSNumberFormatter, I'm able to convert to currency successfully.

    How do I add them up?

    I have a table view, which lists all the products and their prices in the dictionary, formatted as currency. Outside of the table view but in the same class is a UILabel that I want to display the total price of all the products.

    Here is the relevant code under cellForRowAtIndexPath:

    Code:
    	NSNumberFormatter *priceFormatter = [[NSNumberFormatter alloc] init];
    	[priceFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    	NSString *price = [priceFormatter stringFromNumber:[[orderSummaryDictionary objectForKey:[self.orderSummaryArray objectAtIndex:row]] objectForKey:@"Price"]];
    	[priceFormatter release];
    	
    	
    	cell.productName.text = [self.orderSummaryArray objectAtIndex:row];
    	cell.productDescription.text = [[orderSummaryDictionary objectForKey:[self.orderSummaryArray objectAtIndex:row]] objectForKey:@"Description"];
    	cell.productPrice.text = price;
    	cell.productImage.image = [UIImage imageNamed:imageFile];
    	cell.productImage.layer.masksToBounds = YES;
    	cell.productImage.layer.cornerRadius = 5.0;
    
    
    There are two problems: how I add them and how I display the final tally? For the final tally, I need to set the UILabel in ViewDidLoad, but that is called before the above is called. How do I add all the prices, then display that in the UILabel?

    Any help would be amazing.

    Thanks!!
     
  2. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    Why? :confused:

    P.S. Remember that Objective-C is case-sensitive. There is no ViewDidLoad.
     
  3. Luke Redpath macrumors 6502a

    Joined:
    Nov 9, 2007
    Location:
    Colchester, UK
    #3
    This doesn't answer your question, but I'd advise against creating a new number formatter each time in tableView:cellForRowAtIndexPath: as it's creation is quite expensive and will affect your table view scrolling performance. Create one once, and re-use it.
     

Share This Page