Iphone UITableView中的选定行在下一个选项卡BarViewController中显示不同的结果
我一直在试图找出我的代码中这段代码出了什么问题。对于正常的Iphone UITableView中的选定行在下一个选项卡BarViewController中显示不同的结果,iphone,Iphone,我一直在试图找出我的代码中这段代码出了什么问题。对于正常的UITableView,它可以很好地工作,其中包含从本地数据库提取的数据(单击按钮后的结果) 但是,在我将此类似代码用于显示搜索结果的UITableView之后(我尝试进行多类别搜索,但失败),所选行与TabBarViewController上的结果或结果之间出现了错误和差异 以下是链接到选项卡视图控制器的代码 - (void)tableView:(UITableView *)tableView didSelectRowAtInd
UITableView
,它可以很好地工作,其中包含从本地数据库提取的数据(单击按钮后的结果)
但是,在我将此类似代码用于显示搜索结果的UITableView
之后(我尝试进行多类别搜索,但失败),所选行与TabBarViewController
上的结果或结果之间出现了错误和差异
以下是链接到选项卡视图控制器
的代码
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
TabBarViewController *tabBarView = [[TabBarViewController alloc] initWithNibName:@"TabBarViewController" bundle:[NSBundle mainBundle]];
Attraction *att = [attractions objectAtIndex: indexPath.row];
tabBarView.attraction = att;
[self.navigationController presentModalViewController:tabBarView animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[tabBarView release];
}
以下是我的完整代码供您检查:
-(void) checkAndCreateDatabase{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
databaseName = @"funsg.sql";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
//NSLog([NSString stringWithFormat:@"GetData %@", databasePath]);
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];
}
-(void)createEditableCopyOfDatabaseIfNeeded {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"abc.sql"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"abc.sql"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
-(void) readAttractionsFromDatabase {
[self checkAndCreateDatabase];
// Open the database
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = [[NSString stringWithFormat:@"select * from everything "] UTF8String];
//NSLog([NSString stringWithFormat:@"select * from everything"]);
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
NSString *bus = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *desc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *location = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *mrt = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *image = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *type = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *carpark = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
// Create a new animal object with the data from the database
Attraction *att = [[Attraction alloc] initWithName:desc buses:bus add:location type:type mrt:mrt image:image name:name carpark:carpark];
if (attractions == NULL)
// There should not be a NULL name
NSLog(@"Null name!!");
else {
[attractions addObject:att];
// Apparently the addObject function in NSMutableArray does not
// keep a copy of our object, so, we can't release it.
//[name release];
[att release];
}
}
sqlite3_finalize(compiledStatement); // Cleanup the statement
}
else {
NSLog(@"Error retrieving data from database.");
}
sqlite3_close(database);
}
else {
NSLog(@"Error: Can't open database!");
}
}
-(void)viewDidLoad {
[super viewDidLoad];
attractions = [[NSMutableArray alloc] init];
searchedNames = [[NSMutableArray alloc] init];
[self loadData];
}
-(void) insertToDB :(Attraction*) att {
[self checkAndCreateDatabase];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
static sqlite3_stmt *compiledStatement;
sqlite3_exec(database, [[NSString stringWithFormat:@"INSERT INTO everything (Bus,Description,Location,MRT,Name,image,type,Carpark) SELECT '%@','%@','%@','%@', '%@', '%@', '%@', '%@' WHERE NOT EXISTS (SELECT 1 FROM everything WHERE Name = '%@');", att.buses,att.desc,att.add, att.mrt, att.name, att.image, att.type , att.carpark,att.name] UTF8String], NULL, NULL, NULL);
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
-(void) loadData {
//First fetch the data from the JSON
NSURL *url = nil;
NSString *querystring = [NSString stringWithFormat:@"http://mp15.bitproj1.com/testsearch.php"];
url = [NSURL URLWithString:querystring];
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
//NSLog(@"jsonreturn"); // Look at the console and you can see what the restults are
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
// In "real" code you should surround this with try and catch
self.data = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (data==nil){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:@"Unable to update the data." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
else
{
self.rows =[data objectForKey:@"attractions"];
for (int i=0; i<[self.rows count]; i++) {
NSDictionary *dict = [rows objectAtIndex: i];
Attraction* a = [[Attraction alloc] initWithName:[dict objectForKey:@"Description"]
buses:[dict objectForKey:@"Bus"]
add:[dict objectForKey:@"Location"]
type:[dict objectForKey:@"type"]
mrt:[dict objectForKey:@"MRT"]
image:[dict objectForKey:@"image"]
name:[dict objectForKey:@"Name"]
carpark:[dict objectForKey:@"Carpark"]];
//Here we insert the data, when inserting we check for the duplicates. If the record already exists we do not insert. Code also must be optimized later
[self insertToDB:a];
}
}
[jsonreturn release];
[self readAttractionsFromDatabase];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return(1);
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return([searchedNames count]);
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSString *cellText = [searchedNames objectAtIndex:indexPath.row];
[cell.textLabel setText:cellText];
return cell;
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
}
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[searchedNames removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:@""] || searchText==nil) {
// Nothing to search, empty result.
[myTableView reloadData];
return;
}
for (NSString *att in attractions) {
Attraction* p = ((Attraction *)att);
NSRange r = [p.name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound) {
[searchedNames addObject:p.name];
}
}
[myTableView reloadData];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
TabBarViewController *tabBarView = [[TabBarViewController alloc] initWithNibName:@"TabBarViewController" bundle:[NSBundle mainBundle]];
Attraction *att = [attractions objectAtIndex: indexPath.row];
tabBarView.attraction = att;
[self.navigationController presentModalViewController:tabBarView animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[tabBarView release];
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)viewDidUnload {
}
-(void)dealloc {
[data release];
[attractions release];
[super dealloc];
}
@end
-(void)checkAndCreateDatabase{
//检查SQL数据库是否已保存到用户手机中,如果未保存,请将其复制过来
databaseName=@“funsg.sql”;
//获取文档目录的路径并附加数据库名
NSArray*DocumentPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,是);
NSString*documentsDir=[documentPaths objectAtIndex:0];
databasePath=[documentsDir stringByAppendingPathComponent:databaseName];
//NSLog([NSString stringWithFormat:@“GetData%@”,databasePath]);
成功;
//创建一个FileManager对象,我们将使用它来检查状态
//并在需要时复制数据库
NSFileManager*fileManager=[NSFileManager defaultManager];
//检查数据库是否已在用户文件系统中创建
成功=[fileManager fileExistsAtPath:databasePath];
NSString*databasePathFromApp=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:databaseName];
//将数据库从包复制到用户文件系统
[fileManager copyItemAtPath:databasePathFromApp-toPath:databasePath错误:nil];
[文件管理器发布];
}
-(void)CreateEditableCopyOfDatabaseIf需要{
成功;
NSFileManager*fileManager=[NSFileManager defaultManager];
n错误*错误;
NSArray*Path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,是);
NSString*documentsDirectory=[paths objectAtIndex:0];
NSString*writableDBPath=[DocumentsDirectoryStringByAppendingPathComponent:@“abc.sql”];
成功=[fileManager fileExistsAtPath:writableDBPath];
如果(成功)返回;
//可写数据库不存在,因此请将默认数据库复制到适当的位置。
NSString*defaultDBPath=[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@“abc.sql”];
成功=[fileManager copyItemAtPath:defaultDBPath-toPath:writableDBPath错误:&错误];
如果(!成功){
NSAssert1(0,@“无法创建带有消息“@.”,[错误本地化描述])的可写数据库文件;
}
}
-(void)从数据库读取属性{
[自检并创建数据库];
//打开数据库
if(sqlite3_打开([databasePath UTF8String],&database)==SQLITE_正常){
//设置SQL语句并编译它以加快访问速度
const char*sqlStatement=[[NSString stringWithFormat:@“从所有内容中选择*”]UTF8String];
//NSLog([NSString stringWithFormat:@“从所有内容中选择*”);
sqlite3_stmt*编译语句;
if(sqlite3\u prepare\u v2(数据库,sqlStatement,-1,&compiledStatement,NULL)==SQLITE\u OK){
//循环遍历结果并将其添加到提要数组中
while(sqlite3_步骤(compiledStatement)==SQLITE_行){
//从结果行读取数据
NSString*bus=[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement,0)];
NSString*desc=[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement,1)];
NSString*location=[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement,2)];
NSString*mrt=[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement,3)];
NSString*name=[NSString stringWithUTF8String:(char*)sqlite3\u column\u text(compiledStatement,4)];
NSString*image=[NSString stringWithUTF8String:(char*)sqlite3\u column\u text(compiledStatement,5)];
NSString*type=[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement,6)];
NSString*carpark=[NSString stringWithUTF8String:(char*)sqlite3_column_text(compiledStatement,7)];
//使用数据库中的数据创建新的动物对象
景点*att=[[Attraction alloc]initWithName:desc公交车:公交车添加:位置类型:类型地铁:地铁图像:图像名称:名称停车场:停车场];
如果(吸引力==NULL)
//不应该有空名称
NSLog(@“空名称!!”);
否则{
[目标:附件];
//显然,NSMutableArray中的addObject函数没有
//保留一份我们的物品,这样我们就不能释放它了。
//[姓名发布];
[att释放];
}
}
sqlite3_finalize(compiledStatement);//清除语句
}
否则{
NSLog(@“从数据库检索数据时出错”);
}
sqlite3_关闭(数据库);
}
否则{
NSLog(@“错误:无法打开数据库!”);
}
}
-(无效)viewDidLoad{
[超级视图下载];
吸引力=[[NSMutableArray alloc]init];
searchedNames=[[NSMutableArray alloc]init];
[自动加载数据];
}
-(无效)插入图B:(吸引力*)附件{
[自检并创建数据库];
if(sqlite3_打开([databasePath UTF8String],&database)==SQLITE_正常){
静态sqlite3_stmt*编译语句;
sqlite3_exec(数据库,[[NS]
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
if(searching==YES)
{
//retrieve the values from searchedNames array
}
else
{
//retrieve the values from attractions array
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
searching=YES;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
searching=NO;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(searching==YES)
return([searchedNames count]);
else
return [attractions count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSString *cellText;
if(searching==YES)
cellText = [searchedNames objectAtIndex:indexPath.row];
else
cellText = [attractions objectAtIndex:indexPath.row];
[cell.textLabel setText:cellText];
return cell;
}