0

I have an NSArray containing instances of MyCustomObject; each has a NSString called firstName.

The array is sorted by that property, from A to Z.

I want only these objects where firstName starts with the letter A.

For example, suppose my array has 100 objects.

1. Apple
2. Ace
3. Article
4. Ball
5. Cat
6. Camel
....

100. Zebra

Here, I want only "Apple", "Ace", and "Article".

jscs
  • 63,694
  • 13
  • 151
  • 195
Sam Shaikh
  • 1,596
  • 6
  • 29
  • 53
  • Are you worried about performance or is looping through the entire array and doing string lookup an ok path? – Todd Anderson Aug 15 '15 at 16:49
  • 1
    Based on your previous (now deleted) question, you don't want to iterate the list looking just for items starting with A. And then again with B, etc. Iterate the list just once. Put each item in the proper "bucket" based on its starting letter. It would be terrible to iterate the list 26 times. – rmaddy Aug 15 '15 at 17:03
  • BTW - you should update your question to explain what you are really trying to do. The answers you get based on the current question are not going to be appropriate for what you are really trying to do here which is to split the original list into separate arrays for each letter of the alphabet. – rmaddy Aug 15 '15 at 17:12

2 Answers2

1

You can filter an array via predicate

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.firstName beginswith[c] %@",<value>];
NSArray *result = [array filteredArrayUsingPredicate:predicate];

For more detail on NSPredicate visit this link

Adnan Aftab
  • 14,377
  • 4
  • 45
  • 54
0

You can do this:

NSIndexSet* indexes = [array indexesOfObjectsPassingTest:^BOOL(CustomObject* obj, NSUInteger idx, BOOL *stop){
    return [obj.firstName rangeOfString:@"a" options:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch | NSAnchoredSearch].location != NSNotFound;
}];
NSArray* matchingObjects = [array objectsAtIndexes:indexes];
Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • thats great and effecient answer. However is it good to use for loop and put A B C D E ... Z in rangeOfString, to get all arrays separately? @Ken Thomases – Sam Shaikh Aug 15 '15 at 16:58
  • 1
    No, that's not a very efficient approach. You would want to loop over the array just once and add objects to the appropriate array as you examine the first letter of its `firstName`. – Ken Thomases Aug 15 '15 at 17:06
  • No, I want every Alphabet character set must be in a sigle array and that array should be into NSDictionary. like Key 'A' will have all objects whose first name are starting with A, and 'B' key will have all the objects whose first names are starting with B letter. – Sam Shaikh Aug 15 '15 at 19:53