Cocoa Touch:在for循环中添加图像

时间:2011-10-21 23:30:24

标签: objective-c cocoa-touch uiimageview

当我输入一个图像网址数组时,这对我来说很糟糕,我认为这是因为我创建了UIImageView然后尝试再次使用相同的名称!

- (void)cycleImages:(NSArray *)images {


int fromLeft = 5;
   for(int n = 0; n <= [images count]; n++){

   UIImageView *myImageView = [[UIImageView alloc] initWithImage:[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[images objectAtIndex:n]]]]];

   myImageView.frame = CGRectMake(fromLeft, 5, 48, 48); // from left, from top, height, width

   fromLeft = fromLeft + 53;

   //add image view to view
   [self.view addSubview:myImageView];


    NSLog(@"%@", [images objectAtIndex:n]);

}
}

有什么想法吗? 谢谢! DEX

1 个答案:

答案 0 :(得分:0)

首先,您应该使用fast enumeration而不是索引循环。快速枚举更简单,更清晰,更快 - 只要您不需要特定的索引,就没有理由不使用快速枚举。

   UIImageView *myImageView = [[UIImageView alloc] initWithImage:[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[images objectAtIndex:n]]]]];

这假定[images objectAtIndex:n]是一个字符串。这就是你放入数组的内容吗?

另外,由于您使用alloc创建了该图片视图,因此需要将其发布。如果您使用的是ARC,则会自动完成,因此您无需执行任何操作;否则,您需要在将其添加为子视图后发送release或发送autorelease

  

这让我感到震惊......

请更具体。你得到什么样的“崩溃”,以及在什么线上?

如果您收到崩溃日志,请修改您的问题以包含它。