Objective C - Correct way to empty and reload UITableViewController with NSMutableArray

北城余情 提交于 2019-12-25 08:16:03

问题


I have a UITableViewController which uses a NSMutableArray for it's datasource. The array is initially populated in the viewDidLoad method by calling a web service to retrieve the data and populate the NSMutableArray. The user then has the option to enter a search term (in a UISearchBar) and press Search to rerun the web service and repopulate the table list. At this point I need to empty the array and repopulate the table from the results of the web service. My question is what is the correct way to do this without upsetting the repainting of the table view? I can see 2 options :

  1. Call [listArray removeAllObjects]; then [[self tableView] reloadData]; before repopulating the array.

  2. As I restrict the list to a maximum of 200 rows, initialise the array with 200 items and then instead of removing and re-adding when the search is run, use [listArray replaceObjectAtIndex: to replace each row. This would then require an int variable to keep the number of rows returned and use this in the 'tableView numberOfRowsInSection' method so the tableview only displays the number of rows returned.

Hope that makes sense! I'm asking the question because I've had some intermittent errors (EXC_BAD_ACCESS) when re-loading the list and I'm convinced it's to do with how I'm emptying and reloading the list so could use some advice on the best approach.

Any help appreciated,

Jonathan

UPDATE :

Code to initialise array in viewDidLoad :

tableListDataArray = [[NSMutableArray alloc] init];

Once data is retrieved, it is added to the array as follows :

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

The array is released in the dealloc method as follows :

[tableListDataArray release];

回答1:


I personally would go with option 1. You should just be able to use

[tableView reloadData]

without the "self". reloadData will also call the cellForRowAtIndexPath method I believe Don't forget to initialize your NSMutableArray before using it.

myMutableArray  = [[NSMutableArray alloc] initWithCapacity:9001];


来源:https://stackoverflow.com/questions/9708992/objective-c-correct-way-to-empty-and-reload-uitableviewcontroller-with-nsmutab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!