How to add object to NSArray with key from database?
i am using FMDatabase class to open database, its work ok, my problem is how to add object with key to NSArray, see this code
@implementation ViewController {
NSArray *allDevices;
NSArray *searchResult;
}
- (void)viewDidLoad
{
[super viewDidLoad];
FMDatabase *db = [FMDatabase databaseWithPath:[[[NSBundle mainBundle]
resourcePath] stringByAppendingPathComponent:@"db.sqlite"]];
[db open];
FMResultSet *results = [db executeQueryWithFormat:@"select * from allDevices"];
NSString *name; NSString *company;
while ([results next]) {
name = [results stringForColumn:@"name"];
company = [results stringForColumn:@"company"];
allDevices = @[
@{@"name": name, @"company": company}
];
}
[db close];
}
tableView..
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResult count];
} else {
return [allDevices count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
NSDictionary *device;
if ([self.searchDisplayController isActive]) {
device = searchResult[indexPath.row];
} else {
device = allDevices[indexPath.row];
}
NSString *name = device[@"name"];
NSString *company = device[@"company"];
cell.textLabel.text = [NSString stringWithFormat:@"%@ - %@", name, company];
return cell;
}
search code
#pragma mark - UISearchDisplayController delegate methods
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", searchText];
searchResult = [allDevices filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
its working well when i add objects to array manually, like this
allDevices = @[
@{@"name": @"iPhone", @"company": @"Apple"},
@{@"name": @"Galaxy", @"company": @"Samsung"},
@{@"name": @"iPad", @"company": @"Apple"},
];