jaytrixz
jaytrixz

Reputation: 4079

How to Add UIImage to NSMutableArray

I'm trying to add my UIImage from web service to my NSMutableArray using this code:

for (int i=0; i<[totalRowCountString intValue]; i++)
{    
    NSString *criticsRatingString = [[JSON valueForKeyPath:@"movies.ratings.critics_rating"] componentsJoinedByString:@" "];
    NSLog(@"criticsRatingString: %@", criticsRatingString);

    if ([criticsRatingString isEqualToString:@"Certified Fresh"])
    {
        self.ratingImage = [UIImage imageNamed:@"rt_certified_fresh.png"];
    }
    else if ([criticsRatingString isEqualToString:@"Fresh"])
    {
        self.ratingImage = [UIImage imageNamed:@"rt_fresh.png"];
    }
    else if ([criticsRatingString isEqualToString:@"Rotten"])
    {
        self.ratingImage = [UIImage imageNamed:@"rt_rotten.png"];
    }
    else if ([criticsRatingString isEqualToString:@"Spilled"])
    {
        self.ratingImage = [UIImage imageNamed:@"rt_spilled.png"];
    }
    else if ([criticsRatingString isEqualToString:@"Upright"])
    {
        self.ratingImage = [UIImage imageNamed:@"rt_upright.png"];
    }

    [tomatorRatingImages addObject:self.ratingImage];
    NSLog(@"tomatoRatingImages: %@", tomatorRatingImages);
}

But my NSLog for tomatoRatingImages returns NULL. Any ideas why it returns NULL?

UPDATE: my NSMutableArray is already initialized in my viewWillAppear method.

Upvotes: 1

Views: 9557

Answers (4)

SanjayPatel
SanjayPatel

Reputation: 21

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

[tomatorRatingImages  addObject:[UIImage imageNamed:@"rt_spilled.png"]];

[tomatorRatingImages  addObject:[UIImage imageNamed:@"rt_spilled1.png"]];

[tomatorRatingImages  addObject:[UIImage imageNamed:@"rt_spilled2.png"]];

you can enter multiple image in NSMutableArray.

Upvotes: 2

Shashank
Shashank

Reputation: 1753

If you have a property for the NSMutableArray instance, it's better to write getter to initialize it. It takes care of initializing the variable only ones also it gets loaded only when it's required.

   -(NSMutableArray *) tomatorRatingImages {
         if(_tomatorRatingImages == nil) {
               _tomatorRatingImages = [NSMutableArray alloc] init];
         }
         return _tomatorRatingImages;
    }

Upvotes: 1

Lithu T.V
Lithu T.V

Reputation: 20021

Initialize like this

NSMutableArray * tomatorRatingImages =[[NSMutableArray alloc]initWithCapacity:3];

Upvotes: 0

endy
endy

Reputation: 3872

You must initialize the array before adding objects to it.

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

Upvotes: 3

Related Questions