代码之家  ›  专栏  ›  技术社区  ›  Fazil

基于LastName排序-Null异常

  •  0
  • Fazil  · 技术社区  · 10 年前

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

    这里是我的代码

    -(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];
    }      
    
    1 回复  |  直到 10 年前
        1
  •  1
  •   Wain    10 年前

    无论你做什么

    [contact.lastName substringToIndex:1];
    

    如果可能有空字符串,则不安全,因为子字符串请求将始终引发范围异常。你需要更改代码。

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