如何使用数据库中的键将对象添加到NSArray?

如何使用数据库中的键将对象添加到NSArray?

我正在使用FMDatabase类来打开数据库,其工作正常,我的问题是如何添加与NSArray的关键对象,请参阅此代码

@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代码

 #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; } 

它的工作,当我手动添加对象数组,像这样

  allDevices = @[ @{@"name": @"iPhone", @"company": @"Apple"}, @{@"name": @"Galaxy", @"company": @"Samsung"}, @{@"name": @"iPad", @"company": @"Apple"}, ]; 

我find了,

谢谢

  [allDevices addObjectsFromArray:[NSArray arrayWithObjects:[NSMutableDictionary dictionaryWithObjects: [NSArray arrayWithObjects: rowID, name, company, nil] forKeys:[NSArray arrayWithObjects: @"rowID", @"name", @"company", nil]], nil]]; 

看看NSMutableDictionary 。

你可以做这样的事情:

 NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; [dict setObject: obj forKey: @"yourKey"]; 

obj是你想存储的对象。

也看到这个post关于从NSDictionary转换到NSArray。