1

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

现在我想删除所有西海岸高尔夫球场allGolfCourses并创建一个新的array名为eastCoastGolfCourses. 我有另一个NSArraystring objects所有西海岸州(缩写)有关,westCoastStates但很难将这两者联系起来。

如何遍历 allGolfCourses 并删除在 westCoastStates数组中找到状态缩写的所有对象?

westCoastStates 数组:

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

高尔夫球场.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 *state; 包含州缩写,例如:FL

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

4

3 回答 3

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];
于 2012-11-04T15:48:21.563 回答
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++;
    }
}
于 2012-11-04T15:41:59.247 回答
0

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

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

    GolfCourse *currentGolfCourse = (GolfCourse *)obj;
    if(![self.westCoastStates containsObject:currentGolfCourse.state]){
        [self.eastCoastStates addObject:currentGolfCourse];
    }
}];
于 2012-11-04T15:54:47.080 回答