2011-10-21 25 views
0

當我放入一個圖像url陣列時,這會崩潰,我認爲它是因爲我創建了UIImageView,然後嘗試用相同的名稱再次嘗試!Cocoa Touch:在for循環中添加圖像

- (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

回答

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

這是崩潰的我...

請再具體些。你會得到什麼樣的「崩潰」,以及什麼?

如果您收到崩潰日誌,請編輯您的問題以包含它。