Search NSArray for value matching value

后端 未结 8 1135
一生所求
一生所求 2020-11-30 07:52

I have an NSArray of objects, which has a particular property called name (type NSString).
I have a second NSArray of NSStrings which are

相关标签:
8条回答
  • 2020-11-30 08:02

    I like to use this method:

    NSIndexSet *indexes = [_items indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
       return ((MyObject *)obj).name isEqualToString:name];
    }];
    
    if (indexes.count != 0) {
    //extract your objects from the indexSet, and do what you like...
    }
    
    0 讨论(0)
  • 2020-11-30 08:03

    Here's a simple way:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", nameToFind];
    [listOfItems filteredArrayUsingPredicate:predicate];
    
    0 讨论(0)
  • 2020-11-30 08:06
    int count=0;
    
    if (range.location!=NSNotFound)
      {                   
      [searchindex addObject:[NSString stringWithFormat:@"%d",count]];           
      }
    
    0 讨论(0)
  • 2020-11-30 08:08
    NSMutableArray* solutions = [NSMutableArray array];
    
    for (Object* object in objects){
       for (NSString* name in names){
           if ([object.name isEqualToString:name]){
              [solutions addObject:object];
              break; // If this doesnt work remove this
           }
       }
    }
    
    0 讨论(0)
  • 2020-11-30 08:16

    Why not just to use predicates to do that for you?:

    // For number kind of values:
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF = %@", value];
    NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];
    
    // For string kind of values:
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", value];
    NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];
    
    // For any object kind of value (yes, you can search objects also):
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", value];
    NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];
    
    0 讨论(0)
  • 2020-11-30 08:17
    NSMutableArray * foundNames = [NSMutableArray array];
    for (MyObject * objectWithName in objectCollection) {
        if ([names containsObject:objectWithName.name]) {
            [foundNames objectWithName];
        }
    }
    
    0 讨论(0)
提交回复
热议问题