从NSMutableArray

时间:2015-08-20 15:22:20

标签: ios objective-c nsmutablearray nsdictionary nsobject

我将NSObject (人)存储在NSMutableArray (self.tableData)中。

我想使用地址联系人中的部分:按字母顺序对我NSMutableArray中的每个fullName进行排序(已经完成),并使用右侧的索引访问它" A,B,C ,d ..."

我必须得到person.fullName的第一个字母,但我没有成功循环它。 也许我必须使用substringWithRangesubStringToIndex?我不太了解其中的差异。

这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
self.tableData = [[NSMutableArray alloc] init];
    self.contactSectionTitles = [[NSArray alloc] init];
    self.contactIndexTitles = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z"];
    [self getPersonOutOfAddressBook];


    // Dictionary will hold our sub-arrays
    self.dicoAlphabet = [NSMutableDictionary dictionary];

    // Iterate over all the values in our sorted array
    for (Person *person in self.tableData) {

        // Get the first letter and its associated array from the dictionary.
        // If the dictionary does not exist create one and associate it with the letter.
        NSString *firstLetter = [person.fullName substringToIndex:1];
        NSMutableArray *arrayForLetter = [self.dicoAlphabet objectForKey:firstLetter];
        if (arrayForLetter == nil) {
            arrayForLetter = [NSMutableArray array];
            [self.dicoAlphabet setObject:arrayForLetter forKey:firstLetter];
        }

        // Add the value to the array for this letter
        [arrayForLetter addObject:person];
    }

    // arraysByLetter will contain the result you expect
    self.contactSectionTitles = [[self.dicoAlphabet allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

}

的cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.accessoryType = UITableViewCellAccessoryNone;
        Person *person = [self.tableData objectAtIndex:indexPath.row];
//        cell.textLabel.text = person.fullName;

        NSString *sectionTitle = [self.contactSectionTitles objectAtIndex:indexPath.section];
        NSArray *sectionPerson = [self.dicoAlphabet objectForKey:sectionTitle];
        NSString *fullName = [sectionPerson objectAtIndex:indexPath.row];
        cell.textLabel.text = fullName;
        cell.detailTextLabel.text = person.mainNumber;
}

1 个答案:

答案 0 :(得分:2)

substringWithRange 为您提供了两个索引之间的字符串,如下例所示:

NSString *str = @"Hey Alex”;
str = [str substringWithRange:NSMakeRange(1,4)]; //"ey A"

subStringToIndex 将从开头或字符串返回一个子字符串,直到指定的索引为例:

NSString *str = @"Hey Alex";
str = [str substringToIndex:3]; //"Hey"

因此,如果您需要第一个字母,那么最好使用* subStringToIndex *