簡體   English   中英

目標C將自定義對象添加到NSMutableArray

[英]Objective C Adding custom objects into NSMutableArray

我想將數據記錄列表存儲在NSMutableArray中,以便在UITableView中使用。 在其他語言中,我會使用簡單的“類型”結構來定義記錄結構,但是我知道在Obj-C中執行此操作的方法是定義一個新類。 我這樣做如下:

@interface CustSuppListItem : NSObject
@property (nonatomic, copy, readwrite) NSString *acCode;
@property (nonatomic, copy, readwrite) NSString *acCompany;
@property (nonatomic, copy, readwrite) NSString *acContact;
@property (nonatomic, assign, readwrite) double osBalBase;
@property (nonatomic, assign, readwrite) unsigned int acAccStatus;
@end

@implementation CustSuppListItem
@synthesize acCode, acCompany, acContact, osBalBase, acAccStatus;
@end

在我的UITableViewController的viewDidLoad中,我實例化數組:

tableListDataArray = [[NSMutableArray alloc] init];

檢索數據后,將其添加到數組中,如下所示:

CustSuppListItem *custSuppItem = [[CustSuppListItem alloc] init];
[custSuppItem setAcCode:[jsonCustSuppRecord getStringForKey:@"acCode"]];
[custSuppItem setAcCompany:[jsonCustSuppRecord getStringForKey:@"acCompany"]];
[custSuppItem setAcContact:[jsonCustSuppRecord getStringForKey:@"acContact"]];
[custSuppItem setOsBalBase:[jsonCustSuppRecord getDoubleForKey:@"osBalBase"]];
[custSuppItem setAcAccStatus:[jsonCustSuppRecord getIntForKey:@"acAccStatus"]];                             
[tableListDataArray addObject:custSuppItem];                          
[custSuppItem release];

在我的表格cellForRowAtIndexPath方法中,我按如下方式檢索當前單元格的數據:

CustSuppListItem *listDataRecord = [tableListDataArray objectAtIndex:indexPath.row];
[cell.lblCompanyName setText:listDataRecord.acCompany];  // EXC_BAD_ACCESS here
[cell.lblAcCodeContact setText:[NSString stringWithFormat:@"%@, %@",
                                listDataRecord.acCode, listDataRecord.acContact]];
[cell.lblBalance setText:[Utils fmtNumber:listDataRecord.osBalBase withDecPlaces:2]];
[cell.lblStatus setText:[Utils exchAccStatusDesc:listDataRecord.acAccStatus]];
return cell;

在視圖控制器的dealloc方法中,我釋放NSMutableArray:

[tableListDataArray release];

我對Obj-C並不陌生,所以如果有人可以確認我到目前為止所做的一切都有意義並且井井有條,那將是很棒的。 嘗試讀取acCompany屬性時,我收到間歇性EXC_BAD_ACCESS錯誤(請參見行旁的注釋),因此某些內容可能不正確。

任何幫助表示贊賞,

喬納森

乍一看,您的所有代碼對我來說都是合理且正確的。

我要看的幾件事是:

  1. 確認單元lblCompanyName定具有屬性lblCompanyName 如果您嘗試分配給一個不存在的屬性,則會出現這種類型的錯誤。 您是否定義了自定義單元對象類型?

  2. 確認始終是導致EXC_BAD_ACCESSacCompany屬性,而不是對象上的任何屬性。 一種方法是更改cellForRowAtIndexPath方法中各行的順序。

  3. 確認首先正確填充了導致崩潰的listDataRecord。 換句話說,請確認您的jsonCustSuppRecord始終有效。 如果密鑰在jsonCustSuppRecord中不存在,則jsonCustSuppRecord getStringForKey:返回什么?

  4. 在此行設置一個斷點: [tableListDataArray addObject:custSuppItem]; 並每次檢查custSuppItem的內容(這是上面第3點的擴展)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM