UITableView: использовать объект из словаря в качестве заголовка в подробном представлении - PullRequest
1 голос
/ 27 ноября 2011

У меня есть следующий код, чтобы превратить таблицу из строки в словарь:

- (void)viewDidLoad {
    [super viewDidLoad];

    testArray = [[NSArray alloc] init];
    NSString *testString = @"Sam|26,Hannah|22,Adam|30,Carlie|32";
    testArray = [testString componentsSeparatedByString:@","];

    dict = [NSMutableDictionary dictionary];
    for (NSString *s in testArray) {
        testArray2 = [s componentsSeparatedByString:@"|"];
        [dict setObject:[testArray2 objectAtIndex:1] forKey:[testArray2 objectAtIndex:0]];
    }
}

- (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];
    }

    // Configure the cell.
    if (testArray.count >indexPath.row) {
        cell.textLabel.text = [[dict allKeys] objectAtIndex:[indexPath row]];
        cell.detailTextLabel.text = [dict objectForKey:cell.textLabel.text];
    }

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

Мне бы хотелось, чтобы выбранный заголовок строки был установлен в качестве заголовка в подробном представлении.

Я пытался с:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    self.detailController.title = [[dict allKeys] objectAtIndex:[indexPath row]];

    [self.navigationController pushViewController:self.detailController animated:YES];
}

Но я получаю ошибку "EXC_BAD_ACCESS".

Это прекрасно работает, если я использую @ "1" в качестве заголовка, это просто что-то ся полагаю, мой словарный вызов неверен.

Ответы [ 2 ]

0 голосов
/ 27 ноября 2011

Сделать dict сохраненным словарем вместо автоматически выпущенного.

IE объявляет это примерно так:

dict = [[NSMutableDictionary alloc] initWithCapacity: [testArray count]];

в вашем viewDidLoad методе.Обязательно отпустите его, когда вызывается viewDidUnload.

Кроме того, убедитесь, что количество клавиш в вашем dict перед вызовом:

self.detailController.title = [[dict allKeys] objectAtIndex:[indexPath row]];

Итак, я бы сделал:

if(dict && ([[dict allKeys] count] > [indexPath row])
{
    self.detailController.title = 
        [[dict allKeys] objectAtIndex:[indexPath row]];
} else {
    self.detailController.title = @"Here's a problem";
}
0 голосов
/ 27 ноября 2011

Реализовали ли вы эти UITableView методы делегирования? Все это необходимо. Также вы можете выложить более подробную StackTrace.

- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{
    return [resultSet count];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (CGFloat)tableView:(UITableView *)tableView 
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 280.0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...