1

我正在尝试UIImage使用以下代码将我的 web 服务添加到我的 NSMutableArray:

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);
}

但是我的tomatoRatingImages 的NSLog 返回NULL。任何想法为什么它返回NULL?

更新:我的 NSMutableArray 已经在我的 viewWillAppear 方法中初始化。

4

4 回答 4

3

您必须在向其添加对象之前初始化该数组。

NSMutableArray *tomatorRatingImages = [[NSMutableArray alloc] init];
于 2013-02-14T03:09:38.327 回答
2
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"]];

您可以在 NSMutableArray 中输入多个图像。

于 2013-02-14T07:35:57.980 回答
1

如果您有 NSMutableArray 实例的属性,最好编写 getter 来初始化它。它只负责初始化变量,并且仅在需要时才加载它。

   -(NSMutableArray *) tomatorRatingImages {
         if(_tomatorRatingImages == nil) {
               _tomatorRatingImages = [NSMutableArray alloc] init];
         }
         return _tomatorRatingImages;
    }
于 2013-02-14T09:30:41.777 回答
0

像这样初始化

NSMutableArray * tomatorRatingImages =[[NSMutableArray alloc]initWithCapacity:3];
于 2013-02-14T06:51:54.830 回答