【问题标题】:Sort based on LastName - Null exception基于姓氏排序 - 空异常
【发布时间】:2015-03-04 07:44:06
【问题描述】:

在我的代码中,我使用姓氏对联系人进行排序,它显示错误,姓氏为空。如何将空姓氏排序为哈希符号。

这是我的代码

-(void)updateView:(NSArray*)contactsArray{

[self.dataArray removeAllObjects];
[self.sections removeAllObjects];

[self.dataArray addObjectsFromArray:contactsArray];
BOOL found;

for (Contact *contact in self.dataArray)
{
    NSString *c = [[contact.lastName substringToIndex:1] uppercaseString];

    found = NO;

    for (NSString *str in [self.sections allKeys])
    {
        if ([str isEqualToString:c])
        {
            found = YES;
        }
    }

    if (!found)
    {
        [self.sections setValue:[[NSMutableArray alloc] init] forKey:c];
    }
}

// Loop again and sort the books into their respective keys
for (Contact *contact in self.dataArray)
{
    [[self.sections objectForKey:[[contact.lastName substringToIndex:1] uppercaseString]] addObject:contact];
}

// Sort each section array
for (NSString *key in [self.sections allKeys])
{
    [[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES]]];
}

NSLog(@"Check %@",contactsArray);

[self.tableView reloadData];
}      

【问题讨论】:

    标签: ios arrays sorting contact


    【解决方案1】:

    无论你做什么

    [contact.lastName substringToIndex:1];
    

    如果你可能有一个空字符串是不安全的,因为子字符串请求总是会抛出一个范围异常。您需要更改该代码。

    简单的选择是事先检查length,如果它太短,则替换一些其他已知值,以便将所有空姓氏组合在一起。

    【讨论】:

      猜你喜欢
      • 2016-03-02
      • 1970-01-01
      • 2017-09-05
      • 2016-04-16
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      相关资源
      最近更新 更多