Possible Duplicate:
Getting exception as “Collection was mutated while being enumerated”
This question is a continuation of another question I posted earlier How to read in plist data into a data model?
@devdavid’s helped me to get this far…
I have a plist file called “HotelList.plist” and it looks like this:
<array>
<dict>
<key>hotelID</key>
<integer>0</integer>
<key>name</key>
<string>Solmar</string>
// ... more keys and strings ...
</dict>
// ... more hotel entries ...
</array>
I have a “hotel” class describing the keys.
I have a data model class where I would like to read in this plist into an array.
#import "DataModel.h"
#import "Hotel.h"
// Private methods
@interface DataModel ()
@property (nonatomic, retain) NSMutableArray *hotels;
-(void)loadHotels;
@end
@implementation DataModel
@synthesize hotels;
- (id)init {
if ((self = [super init])) {
[self loadHotels];
}
return self;
}
- (void)dealloc {
[hotels release];
[super dealloc];
}
- (void)loadHotels {
NSBundle* bundle = [NSBundle mainBundle];
NSString* plistpath = [bundle pathForResource:@"HotelList" ofType:@"plist"];
hotels = [[NSMutableArray arrayWithContentsOfFile:plistpath]retain];
for (NSDictionary *hotelDict in hotels) {
Hotel *hotel = [[Hotel alloc] init];
hotel.hotelID = [[hotelDict objectForKey:@"hotelID"] intValue];
hotel.name = [hotelDict objectForKey:@"name"];
[hotels addObject:hotel];
[hotel release];
}
}
@end
When I run this, the debugger shows me that each hotel dict was read in but when it reaches the end of the plist (I have about 30 hotels), it tries to go back to the first one and crashes, giving an exception “Collection was mutated while being enumerated”.
The green SIGABRT indicator stops on the
for (NSDictionary *hotelDict in hotels) {
line. Is there something wrong with my for loop? The way I set up the arrays/dictionaries? Or maybe the formatting of the plist is wrong (although I don’t think so because the debugger shows me it is reading it correctly)?
For completeness, I should mention that, yes, the plist file is present and is in the mainBundle, and spelled correctly. Also, the data in the plist is static — I won’t have to save anything new to a file.
Please help!
Use accessors, not ivars directly. Your problem would have been more obvious that way, and you’d avoid the possible leak you have in the assignment of
hotel(ifloadHotelsis every called a second time). Your code reads dictionaries into an array and then tries to appendHotelobjects onto that same array. Here’s what you really meant to say: