【发布时间】:2013-11-23 05:46:25
【问题描述】:
如何使用数据库中的键将对象添加到 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;
}
搜索代码
#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"},
];
【问题讨论】:
-
NSDictionary 用于 iOS 中的 Key-Value 编码,而不是 NSArray。
-
您可以使用名称和公司键值对创建NSDictionary,然后将字典添加到数组中。
-
我在 tableview 中使用这个数组,并使用 filtersArrayUsingPredicate 在其中搜索,它不适用于 NSDictionary
-
能分享一下搜索码sn-p吗
-
@Bhumeshwerkatre 我分享了代码,你看到了吗