Remove particular objects from an array based on objects from another array

好久不见. 提交于 2019-12-04 19:48:31

How about?

NSSet* westCoastStatesSet = [NSSet setWithArray:self.westCoastStates];
NSIndexSet* eastCoastGolfCoursesIndexSet = [allGolfCourses indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    GolfCourse* course = (GolfCourse*)obj;
    if ([westCoastStatesSet containsObject:course.state]) {
        return NO;
    }
    return YES;
}];

NSArray* eastCoastGolfCourses = [allGolfCourses objectsAtIndexes:eastCoastGolfCoursesIndexSet];

Update: I believe this could be condensed with the use of predicates

NSPredicate *inPredicate = [NSPredicate predicateWithFormat: @"!(state IN %@)", self.westCoastStates];
NSArray* eastCoastGolfCourses = [allGolfCourses filteredArrayUsingPredicate:inPredicate];

Pseudo-code:

for (int i = 0; i < allGolfCourses.length;) {
    Course* course = [allGolfCourses objectAtIndex:i];
    if (<is course in one of the "bad" states?>) {
       [allGolfCourse removeObjectAtIndex:i];
    }
    else {
        i++;
    }
}

You can quickly iterate on an array like this:

[self.allGolfCourses enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

    GolfCourse *currentGolfCourse = (GolfCourse *)obj;
    if(![self.westCoastStates containsObject:currentGolfCourse.state]){
        [self.eastCoastStates addObject:currentGolfCourse];
    }
}];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!