Faster NSArray searches using NSDictionary to store indexes as values

Suppose I have a Student class, as shown below:

class Student {
    NSNumber *id;
    NSString *lastName;
    NSString *firstName; 
}

Now that I get the records of all students from the web service, I have an NSArray that stores records for all students. At some point, I need to find an array to find a specific student record based on the name.

Suppose I create a dictionary called studentsFirstNameDictionary.

So by adding objects to the students array, I can do

Student objStudent = [[Student alloc] init];
objStudent.Id = someId;
objStudent.firstName = someName;
objStudent.lastName = someLastName;
[studentsDictionary setValue:iterationCounter forKey:objStudent.firstName];
[students addObject:objStudent];

I want to know if it is useful to create this dictionary to speed up the search, as shown below. Also suppose that in any case the array is necessary and for quick searching I create other dictionaries that store the last name and id as keys and indexes as values, as indicated above:

-(Student*)getStudentByFirstName:(NSString *)firstName {
  int idxOfStudent = [ studentsDictionary valueForKey:firstName];
  return [students idxOfStudent];
}

, , ?

, . , , , ?

P.S.: , , , , , , .

+3
2

, .

-:

Student objStudent = [[Student alloc] init];
objStudent.Id = someId;
objStudent.firstName = someName;
objStudent.lastName = someLastName;
[studentsDictionary setObject:student forKey:objStudent.firstName];

firstName:

Student * theStudent = [ studentsDictionary objectForKey:firstName ] ;

Student studentsDictionary,

NSArray * allStudents = [ studentsDictionary allValues ] ;

, firstName. @rickster

+1

, . , Cocoa, , - Foundation, .

Student, , , , :

-:

NSUInteger index = [studentArray indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
    if ([obj.firstName isEqualToString:desiredFirstName]) {
        *stop = YES;  // keeps us from returning multiple students with same name
        return YES;
    } else
        return NO;
}];
if (index != NSNotFound)
    Student *desiredStudent = [studentArray objectAtIndex:index];

:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstName LIKE %@", desiredFirstName];
NSArray *filteredArray = [studentArray filteredArrayUsingPredicate:predicate];
Student *desiredStudent = [lastObject]; // only object if we assume firstNames are unique

, Student ( KVC-complient accessors) ( ).

, Student:

NSMutableDictionary *studentsByName = [NSMutableDictionary dictionaryWithCapacity:[students count]];
for (Student *student in students)
    [studentsByName setObject:student forKey:[student firstName]];

, .

+10

All Articles