简体   繁体   中英

Removing Objects From NSMutableArray

I have a NSMutableArray that contains all the calendars on my system (as CalCalendar objects):

NSMutableArray *calendars = [[CalCalendarStore defaultCalendarStore] calendars];

I want to remove from calendars any CalCalendar objects whose title does not include the string @"work" .

I've tried this:

for (CalCalendar *cal in calendars) {
    // Look to see if this calendar's title contains "work". If not - remove it
    if ([[cal title] rangeOfString:@"work"].location == NSNotFound) {
        [calendars removeObject:cal];
    }
}

The console is complaining that:

*** Collection <NSCFArray: 0x11660ccb0> was mutated while being enumerated.

And things go bad. Obviously it would seem you can't do what I want to do this way so can anyone suggest the best way to go about it?

Thanks,

While you can not remove items in an array that you are using fast enumeration on, you have some options:

As markhunte noted, -calendars doesn't neccessarily return a mutable array - you'd have to use -mutableCopy to get a mutable array which you can filter:

NSMutableArray *calendars = [[[[CalCalendarStore defaultCalendarStore] 
                                calendars] mutableCopy] autorelease];

... or eg -filteredArrayUsingPredicate: for a immutable filtered copy.

NSArray *calendars = [[CalCalendarStore defaultCalendarStore] calendars];
calendars = [calendars filteredArrayUsingPredicate:myPredicate];

You can not change an array/list you are enumerating (in any language I know of). You will need to create a second list that you will add the calendars that you want to remove, to. Then iterate round the second list, removing the objects from the first. You can then dispose of the second list leaving just the original list with only the calendars you wish to keep hold of.

I noticed NSMutableArray will give the expected results from [[CalCalendarStore defaultCalendarStore] calendars]].

But the returned array from [[CalCalendarStore defaultCalendarStore] calendars]] is actually a NSArray and not an NSMutableArray. (also has a warning come up about expected structure)

This is all new to me so am I missing something here? or is this the correct way of going about this task..

NSMutableArray *workCals= [[NSMutableArray  alloc] initWithCapacity:2];
[workCals addObjectsFromArray: [[CalCalendarStore defaultCalendarStore] calendars]];


NSString *title = @"work";

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"title contains[c] %@",title ]; 
[workCals filterUsingPredicate:predicate];
NSLog(@"workCals %@",workCals );
[workCals release];

Cheers.

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