繁体   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