In my iphon app , I’m reading from sqlite db into NSMutableArray *sales and I want to assign the data in sales into a cell in TableView.
How can I do it?
Here is my code:
In Controller:
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *result = nil;
if ([tableView isEqual:self.myTableView]){
static NSString *TableViewCellIdentifier = @"MyCells";
result = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];
if (result == nil){
result = [[UITableViewCell alloc]
initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier:TableViewCellIdentifier];
}
AppDelegate *appDelegate = ( AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate readSalesFromDatabase];
// ***here is where I'm trying to retrive the data***
// when I run the simulator, at this point I receive 'SIGABRT'
=====> result = [sales objectAtIndex:indexPath.row];
}
return result;
}
In Delegate:
-(void) readSalesFromDatabase {
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select us.userID from UsersSale us order by us.saleID";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSInteger auserID = sqlite3_column_int(compiledStatement, 0);
// Create a new Sale object with the data from the database
SelectFromList *sfl = [[SelectFromList alloc] initWithName:auser];
// ***here is where I'm inserting the data to NSMutableArray *sales **
[selectFromListController.sales insertObject:sfl atIndex:count];
[sfl release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
@end
First, consider calling ‘[appDelegate readSalesFromDatabase]’ on viewDidLoad or in your view controller’s init method as you’re invoking this for every row rendered. That’s probably not what you want for performance.
Second, you should check to see what is in the ‘sales’ array and make sure there is data in it. If the indexPath.row value exceeds the size of the array, it’s likely that you’re not returning the actual and correct number of rows in ‘tableView:numberOfRowsInSection:’. In that case, you’re being asked for data that may not exist in your backing store.
Also, you may want to think of your UITableView usage not as ‘assigning data into the table’s cell’ but instead, ‘return data for the particular cell that is being rendered currently’.