简体   繁体   中英

Cocoa Touch: Adding images in for loop

this is crashing on me when I put in an array of image urls, I think its because of me creating the UIImageView and then trying to do it again with the same name!

- (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]);

}
}

Any ideas? Thanks! Dex

First, you should use fast enumeration instead of an index loop. Fast enumeration is simpler, clearer, and faster—whenever you don't specifically need an index for something, there is no reason not to use fast enumeration.

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

This assumes that [images objectAtIndex:n] is a string. Is that what you put into the array?

Also, because you created that image view with alloc , you need to release it. If you're using ARC, that's done automatically, so you don't need to do anything; otherwise, you need to either send it release after adding it as a subview or send it autorelease .

this is crashing on me …

Please be more specific. What sort of “crash” do you get, and on what line?

If you get a crash log, please edit your question to include it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM