问题
Setup: Have a UITableView
which shows US golf courses with name, street, state etc.
UITableView's
data source is a NSMutableArray
of objects from my class GolfCourse
called allGolfCourses
.
Now I like to remove all west coast golf courses from allGolfCourses
and create a new array
called eastCoastGolfCourses
. I have another NSArray
with string objects
of all west coast states (Abbreviations) called westCoastStates
but having a hard time connecting these two.
How do I iterate through allGolfCourses and remove all objects which have a state Abbreviations found in westCoastStates
array?
westCoastStates Array:
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
Note: NSString *state; contains the state abbreviation for example: FL
I know how to do this with a single argument but don't know how to check against all strings from westCoastStates
array. Hope you can help.
回答1:
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];
回答2:
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++;
}
}
回答3:
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];
}
}];
来源:https://stackoverflow.com/questions/13219988/remove-particular-objects-from-an-array-based-on-objects-from-another-array