开发者

Filter Through Array

How would I filter through an array and return values that con开发者_开发知识库tain a certain part of a string? I have a text box where, for the sake of this example, a user puts in 25, and then hits a "Done" button.

Example:

Original Array {25-1002, 25-1005, 12-1003, 1000-0942, 1-1, 234-25}

I want it to return (after sorting through it and pulling the values I want):

New Array {25-1002, 25-1005}

Please note that in the original array, the last value of 234-25 has a 25 in it as well but is not pulled through. It needs to be the number on the first part of the hyphen.

Thanks in advance!


Use the -filteredArrayUsingPredicate: method, like this:

NSString *searchText = [someField.text stringByAppendingString:@"-"];
newArray = [originalArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^(NSString *value, NSDictionary *bindings){
    return ([value rangeOfString:searchText].location != NSNotFound)
}]];

Note that blocks (the ^{} thing) aren’t available pre-iOS 4, so you’ll have to use another of NSPredicate’s constructors if you’re targeting 3.x devices as well.


as an easy to understand answer (not using NSPredicate, which can be intimidating (but is really the correct way to do it)):

NSMutableArray *myNewArray = [[NSMutableArray alloc] init];
for (NSString *string in myArray) {
    if([[string substringToIndex:3] isEqualToString @"25-"])
    {
        [myNewArray addObject:string];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜