Сбой приложения при прокрутке TableView - PullRequest
1 голос
/ 05 октября 2011

Мое приложение падает, когда я прокручиваю свой TableView.Сначала в моем методе viewDidLoad загружается словарь из файла, и для этого словаря я перечисляю все ключи.

 - (void)viewDidLoad {

     [super viewDidLoad];

     NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];      

     path = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"currency.archive"]]; 

     banks = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

     keys = [banks allKeys];

     // set date for last update 
     dayMonthYear.text = [banks objectForKey:@"Last Updated"];
}

В моем cellForRowAtIndexPath я заполняю ячейки данными из этого словаря.В любом случае, когда мое приложение запускается, все выглядит нормально, первые пять строк отображаются правильно, но когда я начинаю прокручивать мое приложение, происходит сбой.Моя идея заключается в том, что проблема здесь с автоматически выпущенным объектом, я пытался сохранить их и после их использования выпустить, но безуспешно.Отладчик показывает, что моя проблема в строке с жирным шрифтом

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell %d_%d",indexPath.section,indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {      

        [[NSBundle mainBundle] loadNibNamed:@"CurrencyTableCell" owner:self options:nil];

        cell = currencyTableCell;

        //don't show selected cell
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //set height
        self.cellHeight = cell.frame.size.height;
    }    

    // Fetch currency 
    NSString *currentCurrency = [keys objectAtIndex:indexPath.row];

    NSDictionary *fetchedCurrency = [banks objectForKey:currentCurrency];

    **NSString *name = [fetchedCurrency objectForKey:@"Currency Name"];**

    currencyTitle.text = name;

    NSString *charCode = [fetchedCurrency objectForKey:@"Code"];

    currencyCode.text = charCode;

    NSString* formattedNumber = [NSString stringWithFormat:@"%.02f",[[fetchedCurrency  objectForKey:@"Value"] floatValue]];

    if ([formattedNumber length] == 4) {
        formattedNumber = [NSString stringWithFormat:@"%@%@",@"0",formattedNumber];
    }

    buyPrice.text = formattedNumber;

    return cell;    
}

Ответы [ 3 ]

0 голосов
/ 05 октября 2011

В результате обсуждения [banks objectForKey:@"Last Updated"] дает вам NSString, а не NSDictionary!

Вы можете обойти эту ошибку, выполнив

if ([[banks objectForKey:currentCurrency] class] == [NSDictionary class]) { 
    ... rest of the code here .. 
}
0 голосов
/ 05 октября 2011

- [NSCFString objectForKey:]: нераспознанный селектор отправлен на экземпляр 0x4bab9c0

Ваши переменные банков и ключей не сохраняются, как упоминалось в другом ответе, но это не ошибка.

Согласно этой ошибке, ваш fetchedCurrency объект является NSString, а не NSDictionary. Проверьте формат вашего файла currency.archive.

0 голосов
/ 05 октября 2011

Измените ваш viewDidLoad с кодом ниже, он будет работать

- (void)viewDidLoad {
     [super viewDidLoad];

     NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];      
     path = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"currency.archive"]]; 
     banks = [[NSDictionary alloc] initWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:path]];
     keys = [[NSArray alloc] initWithArray:[banks allKeys]];
     // set date for last update 
     dayMonthYear.text = [banks objectForKey:@"Last Updated"];
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...