I have a nethod to refresh the content of a UIScrollView. Within the ScrollView there are several UIImageViews and some UILabels.
I do clean the content of the scrollView with the following code:
for (int i = [publicationsScrollView.subviews count] -1; i>=0; i--) {
NSLog(@"Deleting SubView: %@", [[publicationsScrollView.subviews objectAtIndex:i] class]);
if ([[publicationsScrollView.subviews objectAtIndex:i] isKindOfClass:[UIButton class]] || [[publicationsScrollView.subviews objectAtIndex:i] isKindOfClass:[UIButtonLongTap class]] || [[publicationsScrollView.subviews objectAtIndex:i] isKindOfClass:[UILabel class]] || [[publicationsScrollView.subviews objectAtIndex:i] isKindOfClass:[UIImageView class]]) {
NSLog(@"Deleting SubView: %@", [[publicationsScrollView.subviews objectAtIndex:i] class]);
[[publicationsScrollView.subviews objectAtIndex:i] removeFromSuperview];
}
if ([[publicationsScrollView.subviews objectAtIndex:i] isKindOfClass:[iCarousel class]]) {
NSLog(@"carousel: View is in Scrollview");
}
}
This code ran fine for some days. Now i recieve an error during refresh in console:
refreshWorkSpace: deleting all subviews (11)
2011-11-25 14:04:52.826 CatalogService[45054:fb03] Deleting SubView: UILabel
2011-11-25 14:04:52.827 CatalogService[45054:fb03] Deleting SubView: UILabel
2011-11-25 14:04:52.839 CatalogService[45054:fb03] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 10 beyond bounds [0 .. 9]'
*** First throw call stack:
(0x1e8c052 0x231fd0a 0x1e78db8 0x6945 0x5826 0x1e8dec9 0xddc5c2 0xddc55a 0xe81b76 0xe8203f 0xe81bab 0xecfa99 0xed1407 0xe0193f 0xe01c56 0xde8384 0xddbaa9 0x28b6fa9 0x1e601c5 0x1dc5022 0x1dc390a 0x1dc2db4 0x1dc2ccb 0x28b5879 0x28b593e 0xdd9a9b 0x2e6d 0x2de5 0x1
I can not understand what’s happening here. I loop through the subviews (count should give me the number of existing subviews !?). Why could the Index be out of Bounds !?
I would suspect the exception is being thrown on this line:
in the case where
[[publicationsScrollView.subviews objectAtIndex:i] removeFromSuperview]has just executed there will no longer be an object at index ‘i’. This would only happen if the last subview in the array was one of the types you delete – otherwise the access would be harmless.To fix, you could just add a
continueafter theremoveFromSuperviewcall.