Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 209
Garry Pettet Avatar asked Jan 28 '26 16:01

Garry Pettet


1 Answers

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

  • filter the array using -filterUsingPredicate:
  • use index-based iteration
  • remove via index sets, e.g. using -indexesOfObjectsPassingTest:
  • build an array of the objects to remove and use e.g. -removeObjectsInArray:

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 e.g. -filteredArrayUsingPredicate: for a immutable filtered copy.

NSArray *calendars = [[CalCalendarStore defaultCalendarStore] calendars];
calendars = [calendars filteredArrayUsingPredicate:myPredicate];
like image 164
Georg Fritzsche Avatar answered Jan 31 '26 07:01

Georg Fritzsche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!