Xcode найти строку раздела таблицы в подробной текстовой метке

У меня есть индекс, настроенный для моей таблицы, и я могу вернуть правильные массивы для textLabel.text в соответствии с заголовком раздела. Моя проблема в том, что у меня есть отдельный массив, который мне нужно вернуть в файле detailTextLabel.text.

Это просто повторяется в каждом разделе, начиная с первого индекса из первого раздела. Например:

А

яблоко

яблоко

Аллигатор

аллигатор

Б

Мяч

яблоко

Летучая мышь

аллигатор


Я создал индексные символы и заголовки таблиц. Это то, что я должен вернуть камеру.

NSString *alphabet = [arrayIndex objectAtIndex:[indexPath section]];
            //---get all of First array's beginning with the letter---
            NSPredicate *predicate =
            [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
            NSArray *firstArray = [First filteredArrayUsingPredicate:predicate]; 
            NSArray *secondArray = [Second filteredArrayUsingPredicate:predicate]; 

    if ([FirstArray count]>0) {
        //---extract the relevant state from the states object---
        NSString *cellValue = [firstArray objectAtIndex:indexPath.row];



      //<--This line throws and error assuming it is trying to find the first letter to return the detail text -->  
    NSString *cellValueA = [secondArray objectAtIndex:indexPath.row];
//Returns value from first section and row in all section//
            //NSString *cellValueA = [Second objectAtIndex:indexPath.row]; 
            cell.textLabel.text = cellValue;
            cell.detailTextLabel.text = cellValueA;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }    

Как найти строку, соответствующую первому массиву, чтобы вернуть правильный индекс во втором массиве. Любая помощь приветствуется. Спасибо :-)


ПОЛНЫЙ КОД

-(void)loadSQL {
    // Path to the database
    NSString* dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"DATABASE_NAME.sqlite"];
    NSLog(@"databasePath: %@",dbPath);
    sqlite3 *database;
    NSString *firstString;
    NSString *secondString;

    // Open the database
    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
        NSString *querySQL = [NSString stringWithFormat: 
                              @"SELECT * FROM songs WHERE items LIKE %@ ", viewItems];

        const char *sql = [querySQL UTF8String];

        sqlite3_stmt *compiledStmt;
        // Fetch all names
        if (sqlite3_prepare_v2(database, sql, -1, &compiledStmt, NULL) == SQLITE_OK) {
            // Append each name
            while (sqlite3_step(compiledStmt) == SQLITE_ROW) {

                const char* cFirst = (char*)sqlite3_column_text(compiledStmt, 2);
                        const char* cSecond = (char*)sqlite3_column_text(compiledStmt, 3);

                if (cFirst == NULL)
                    // There should not be a NULL name
                    NSLog(@"Null name!!");

                else {
                firstString = [NSString stringWithUTF8String:cName];
                            secondString = [NSString stringWithUTF8String:cArtist];

                [First addObject:firstString];
                [Second addObject:secondString];


                    //[First release];
                    //[Second release];
                }
            }
            sqlite3_finalize(compiledStmt); // Cleanup the statement
        }
        else {
            NSLog(@"Error retrieving data from database.");
        }
        sqlite3_close(database);
    }
    else {
        NSLog(@"Error: Can't open database!");
    }

//Creating section with 1st letter of the First field//
    for (int i=0; i<[First count]-1; i++){
        //---get the first char of each state---
        char alphabet = [[First objectAtIndex:i] characterAtIndex:0];
        NSString *uniChar = [NSString stringWithFormat:@"%C", alphabet];
        //---add each letter to the index array---
        if (![arrayIndex containsObject:uniChar])
        {
            [arrayIndex addObject:uniChar];
        }
    }         
}





#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (searching)
        return 1;
    else
        return [arrayIndex count];
}

//---set the title for each section---
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (searching)
        return nil;

    else        
        return [arrayIndex objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (searching)
        return([searchedFirst count]);
    else{
        //return([First count]);
        NSString *alphabet = [songIndex objectAtIndex:section];
        NSPredicate *predicate =[NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
        NSArray *firstArray = [First filteredArrayUsingPredicate:predicate];
        return [firstArray count];

    }
}

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

    if (searching) {
        return nil;
    }

    return arrayIndex;
}


//return the cell info
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    if(searching) {
        cell.textLabel.text =  [searchedFirst objectAtIndex:indexPath.row];
        cell.detailTextLabel.text = [searchedSecond objectAtIndex:indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else{
        //---get the letter in the current section---
        NSString *alphabet = [arrayIndex objectAtIndex:[indexPath section]];
        //---get all states beginning with the letter---
        NSPredicate *predicate =
        [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
        NSArray *firstArray = [First filteredArrayUsingPredicate:predicate]; 
        NSArray *secondArray = [Second filteredArrayUsingPredicate:predicate]; 

        if ([songArray count]>0) {
            NSString *firstValue = [firstArray objectAtIndex:indexPath.row];
            NSString *secondValue = [secondArray objectAtIndex:indexPath.row];

            cell.textLabel.text = firtValue;
            cell.detailTextLabel.text = secondValue;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }

    }
    return cell;


}

person Far    schedule 28.06.2012    source источник
comment
Это больше мета-ответ, чем ответ. Попытка отслеживать несколько массивов и связывать их через номер индекса — плохая идея в целом именно по этой причине. Гораздо лучше было бы создать настраиваемый объект, содержащий необходимую информацию как для textLabel, так и для detailTextLabel, и один массив, содержащий эти объекты. Таким образом, как только вы найдете нужный объект, у вас будет все фрагменты информации вместе.   -  person Phillip Mills    schedule 28.06.2012
comment
Привет спасибо. Вы можете привести пример этого? Я новичок в xcode. Здесь я сделал отдельные массивы из оператора sql из 2 полей. Я не уверен, как добавить эти два.   -  person Far    schedule 28.06.2012
comment
Если вы можете показать код, который в настоящее время заполняет First и Second, я постараюсь внести предложения по его изменению. (По сути, вы хотите создать новый класс, который наследуется от NSObject и содержит две строки в качестве свойств. Затем, вместо того, чтобы добавлять что-то к First и что-то еще к Second, вы помещаете обе эти вещи в один из ваших новых объектов и сохраняете это в массив.)   -  person Phillip Mills    schedule 28.06.2012
comment
хорошо, я добавил код выше. Я думаю, что пытаюсь понять концепцию добавления двух отдельных массивов в один, но все еще имею его в TextLabel и DetailTextLabel, лол.   -  person Far    schedule 28.06.2012


Ответы (2)


Я не уверен, что понимаю, что вам нужно, но если вы ищете индекс в массиве данного объекта, вы можете использовать:

индексОбъекта:

Возвращает наименьший индекс, соответствующее значение массива которого равно данному объекту.

   - (NSUInteger)indexOfObject:(id)anObject

(ссылка)

person sergio    schedule 28.06.2012

Отвечая на вопрос из комментариев о реструктуризации....

Сначала создайте собственный класс:

// CellLabels.h
#import <Foundation/Foundation.h>

@interface CellLabels : NSObject
@property (nonatomic, copy) NSString *firstText;
@property (nonatomic, copy) NSString *secondText;
@end

//CellLabels.m
#import "CellLabels.h"

@implementation CellLabels
@synthesize firstText = _firstText;
@synthesize secondText = _secondText;
@end

Вместо First и Second создайте и инициализируйте один NSMutableArray с именем cellData. Заменять...

[First addObject:firstString];
[Second addObject:secondString];

...с участием...

CellLabels *labels = [[CellLabels alloc] init];
labels.first = firstString;
labels.second = secondString;
[cellData addObject:labels];

Затем ваша фильтрация массива работает путем сравнения "SELF.firstText", а ваши ссылки на массив работают с использованием:

CellLabels *labels = [filteredArray objectAtIndex:indexPath.row];
cell.textLabel.text = labels.firstText;
cell.detailTextLabel.text = labels.secondText;

(Хорошо, я не проверял, чтобы убедиться, что все скомпилировано, но это должно дать вам представление.)

person Phillip Mills    schedule 28.06.2012
comment
хорошо, спасибо за это. У меня получилось, что я застрял на простом вызове массива labels.firstText для получения первых букв и возврата строк. Я уверен, что разберусь. :-) - person Far; 28.06.2012