отсортированное значение не отображается должным образом в табличном представлении в iphone - PullRequest
0 голосов
/ 15 марта 2012

Код работает правильно, но когда я добавляю более одного значения для определенного алфавита, он повторяетсяЕсли для этого алфавита есть одно значение, данные отображаются правильно - где я ошибаюсь?

    - (void)viewDidLoad {
    [super viewDidLoad];

    PeopleModal *dislist = [[PeopleModal alloc]init];
    [dislist getAll];

    personarray = [[NSMutableArray alloc]init];
    [personarray addObjectsFromArray:dislist.Peoplelistarray];
    //short the personarray value:
    NSSortDescriptor *asortDescriptor;
    asortDescriptor=[NSSortDescriptor sortDescriptorWithKey:@"FirstName" ascending:YES selector:@selector(caseInsensitiveCompare:)];

    NSArray *sortDescriptors=[NSArray arrayWithObject:asortDescriptor];
    [self.personarray sortUsingDescriptors:sortDescriptors];

    //---create the index---
    Frstname = [[NSMutableArray alloc] init];

        //check
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for (NSDictionary *row in personarray) {
        [tempArray addObject:[row valueForKey:@"FirstName"]];

        for (int i=0; i<[tempArray count]-1; i++){
            char alphabet = [[tempArray objectAtIndex:i] characterAtIndex:0];
            NSString *uniChar = [NSString stringWithFormat:@"%C", alphabet];
            if (![Frstname containsObject:uniChar]){  
                [Frstname addObject:uniChar];           
            }
        }

    }

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.

    return [Frstname count];

}

//---set the title for each section---
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    return [Frstname objectAtIndex:section];

}

//---set the index for the table---
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

        return Frstname;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (isSearchOn) {
        return [searchResult count];
    } else{
//return personarray.count;
    //---get the letter in each section; e.g., A, B, C, etc.---
    NSString *alphabet = [Frstname objectAtIndex:section];
    //---get all FirstName beginning with the letter---beginswith
    NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@"SELF.FirstName beginswith[c] %@", alphabet];
    NSArray *Names = [personarray  filteredArrayUsingPredicate:predicate];
    //---return the number of Names beginning with the letter---
    return [Names count];
    }

}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [Mytableview dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }
    if (isSearchOn) {
        NSString *cellValue = [searchResult objectAtIndex:indexPath.row];
        cell.textLabel.text = cellValue;
    }
    else {

    //---get the letter in the current section---
    NSString* alphabet = [Frstname objectAtIndex:[indexPath section]];
    //---get all states beginning with the letter---
    NSPredicate *predicate =
        [NSPredicate predicateWithFormat:@"SELF.FirstName beginswith[c] %@", alphabet];
    //[NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
    //NSArray *Names = [[personarray valueForKey:@"FirstName"] filteredArrayUsingPredicate:predicate];
        NSArray *Names = [personarray  filteredArrayUsingPredicate:predicate];
    //NSArray *lastNames = [[personarray valueForKey:@"LastName"] filteredArrayUsingPredicate:predicate];
    if ([Names count]>0) {
        //---extract the relevant firstname from the Names object---


        PeopleModal *locallist = [Names objectAtIndex:indexPath.row];

        cell.textLabel.text = locallist.FirstName;
        cell.detailTextLabel.text=locallist.LastName;           
    }   

    }


    return cell;





}

Ответы [ 3 ]

0 голосов
/ 15 марта 2012

вы отлаживали свой код ??вы получаете повторяющиеся значения из-за этих строк

  for (int i=0; i<[tempArray count]-1; i++){
        char alphabet = [[tempArray objectAtIndex:i] characterAtIndex:0];
        NSString *uniChar = [NSString stringWithFormat:@"%C", alphabet];
        if (![Frstname containsObject:uniChar]){  
            [Frstname addObject:uniChar];

        }

здесь вы запускаете цикл for в другую сторону цикла loop.so, он будет вызываться для каждой итерациивместо цикла for используйте

  char alphabet = [[[row valueForKey:@"FirstName"] characterAtIndex:0];
    NSString *uniChar = [NSString stringWithFormat:@"%C", alphabet];
    if (![Frstname containsObject:uniChar]){  
        [Frstname addObject:uniChar];

Я надеюсь, что вы пишете код, чтобы получить уникальные первые символы ...

0 голосов
/ 15 марта 2012

при условии, что вы пытаетесь вставить все недублированные символы из имени в массиве Frstname, измените это:

    //check
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (NSDictionary *row in personarray) {
    [tempArray addObject:[row valueForKey:@"FirstName"]];

    for (int i=0; i<[tempArray count]-1; i++){
        char alphabet = [[tempArray objectAtIndex:i] characterAtIndex:0];
        NSString *uniChar = [NSString stringWithFormat:@"%C", alphabet];
        if (![Frstname containsObject:uniChar]){  
            [Frstname addObject:uniChar];
        }
    }

}

для этого:

    //check
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (NSDictionary *row in personarray) {
    [tempArray addObject:[row valueForKey:@"FirstName"]];

    for (int i=0; i<[tempArray count]-1; i++){
        char alphabet = [[tempArray objectAtIndex:i] characterAtIndex:0];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] '%c'", alphabet];
        NSArray *duplicates = [Frstname filteredArrayUsingPredicate:predicate];
        if ([duplicates count] == 0) {
            [Frstname addObject:uniChar];
        }
    }
 }
0 голосов
/ 15 марта 2012

Да, вы используете containsObject, и оно всегда будет возвращать false, потому что id этого объекта - новая NSString, поэтому ваш код добавляет то же значение NSString в массив.Попробуйте что-то вроде этого:

NSArray *duplicates = [Frstname filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%C", alphabet]];
if ([duplicates count] == 0) {
    [Frstname addObject:uniChar]
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...