从NSMutableArray中删除对象

Gar*_*tet 2 xcode cocoa calendar objective-c nsmutablearray

我有一个NSMutableArray,它包含我系统上的所有日历(作为CalCalendar对象):

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

我想从标题不包含字符串的calendars任何CalCalendar对象中删除@"work".

我试过这个:

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

控制台抱怨说:

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

事情变坏了.显然你似乎不能做我想做的事情所以有人能建议最好的方法吗?

谢谢,

Geo*_*che 7

虽然您无法删除正在使用快速枚举的数组中的项目,但您有以下选项:

正如markhunte所指出的那样,-calendars不一定会返回一个可变数组 - 你必须使用它-mutableCopy来获得一个可以过滤的可变数组:

NSMutableArray *calendars = [[[[CalCalendarStore defaultCalendarStore] 
                                calendars] mutableCopy] autorelease];
Run Code Online (Sandbox Code Playgroud)

...或者例如-filteredArrayUsingPredicate:对于不可变的过滤副本.

NSArray *calendars = [[CalCalendarStore defaultCalendarStore] calendars];
calendars = [calendars filteredArrayUsingPredicate:myPredicate];
Run Code Online (Sandbox Code Playgroud)