根据另一个数组中的对象从数组中删除特定对象

时间:2012-11-04 15:34:38

标签: iphone ios filter nsarray

设置:有UITableView显示美国高尔夫球场的名称,街道,州等。 UITableView's数据源是我的班级NSMutableArrayGolfCourse个名为allGolfCourses的对象。

现在,我想从allGolfCourses移除所有西海岸高尔夫球场,并创建一个名为array的新eastCoastGolfCourses。我有另一个NSArray,其中string objects所有西海岸州(缩写)都称为westCoastStates,但很难连接这两个州。

如何遍历allGolfCourses并删除所有具有westCoastStates数组中的缩写的对象?

westCoastStates数组:

self.westCoastStates = [NSMutableArray arrayWithObjects:
                        @"CH",
                        @"OR",
                        @"WA",
                        nil];

GolfCourse.h

@interface GolfCourse : NSObject

@property (nonatomic, strong) NSString *longitude;
@property (nonatomic, strong) NSString *latitude;
@property (nonatomic, strong) NSString *clubName;
@property (nonatomic, strong) NSString *state;
@property (nonatomic, strong) NSString *courseInfo;
@property (nonatomic, strong) NSString *street;
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSString *clubID;
@property (nonatomic, strong) NSString *phone;

@end

注意:NSString *状态;包含州缩写,例如:FL

我知道如何使用单个参数执行此操作但不知道如何检查来自westCoastStates数组的所有字符串。希望你能帮忙。

3 个答案:

答案 0 :(得分:3)

怎么样?

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];

更新:我相信这可以通过使用谓词来缩小

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

答案 1 :(得分:0)

的伪代码:

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++;
    }
}

答案 2 :(得分:0)

您可以快速迭代这样的数组:

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

    GolfCourse *currentGolfCourse = (GolfCourse *)obj;
    if(![self.westCoastStates containsObject:currentGolfCourse.state]){
        [self.eastCoastStates addObject:currentGolfCourse];
    }
}];
相关问题