[英]App crashing when scrolling TableView
當我滾動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;
}
用下面的代碼更改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"];
}
討論的結果是, [banks objectForKey:@"Last Updated"]
為您提供了NSString,而不是NSDictionary!
您可以通過執行以下操作來解決此錯誤
if ([[banks objectForKey:currentCurrency] class] == [NSDictionary class]) {
... rest of the code here ..
}
-[NSCFString objectForKey:]:無法識別的選擇器已發送到實例0x4bab9c0
如另一個答案中所述,不會保留您的bank和key變量,但這不是錯誤。
根據此錯誤,您的fetchedCurrency
對象是NSString
,而不是NSDictionary
。 檢查currency.archive文件的格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.