将sqlite查询的值分配给Nsmutablearray

时间:2012-07-09 12:28:09

标签: objective-c database xcode sqlite

我试图在Xcode 4.3.3上创建一个搜索引擎,这是一个搜索UITableView的搜索栏。

首先我尝试创建没有动态数据库且没有sqlite连接的搜索引擎,它工作正常,如果在NSMutableArray中预定义的静态元素之间进行搜索,我就有能力。

现在我没有在数组中静态预定义元素,而是想访问sqlite数据库并执行查询,将结果作为单元格字段。 我曾尝试使用FMDB进行连接,但问题是我无法实现。

这是我的代码,我做错了什么?

//
//  FilterDemoTableViewController.m
//  Created by Elias Rahme.
//  Copyright (c) ERC.
//

#import "ViewController.h"
#import "DetailsViewController.h"
#import "Food.h"
#import "FMDatabase.h"

@implementation ViewController

@synthesize allTableData;
@synthesize filteredTableData;
@synthesize searchBar;
@synthesize isFiltered;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    searchBar.delegate = (id)self;
    NSString *path  = [[NSBundle mainBundle] pathForResource:@"SampleDB" ofType:@"sqlite"];
    FMDatabase *db  = [[FMDatabase alloc] initWithPath:path];
    [db open];
    if (![db open]) {
        NSLog(@"Could not open db.");
    }
    else{
    NSLog(@"Database is opened");
    }
    FMResultSet *fResult= [db executeQuery:@"SELECT a_id FROM Description where desc_id=1"];
    if( !fResult){

        NSLog(@"Could not execute query");
      }
    else{
        NSLog(@"Query executed");
    }
    eleData = [fResult stringForColumn:@"desc"];

  //  NSLog([fResult stringForColumn:@"desc"]);

    allTableData = [[NSMutableArray alloc] initWithObjects:
                    [[Food alloc] initWithName:@"test" andDescription:@"TEst" ], 
                    [[Food alloc] initWithName:@"Steak" andDescription:@"Medium"], 
                    [[Food alloc] initWithName:@"Salad" andDescription:@"Caesar"], 
                    [[Food alloc] initWithName:@"Salad" andDescription:@"Bean"], 
                    [[Food alloc] initWithName:@"Fruit" andDescription:@"Apple"], 
                    [[Food alloc] initWithName:@"Potato" andDescription:@"Baked"], 
                    [[Food alloc] initWithName:@"Potato" andDescription:@"Mashed"], 
                    [[Food alloc] initWithName:@"Bread" andDescription:@"White"], 
                    [[Food alloc] initWithName:@"Bread" andDescription:@"Brown"], 
                    [[Food alloc] initWithName:@"Hot Dog" andDescription:@"Beef"], 
                    [[Food alloc] initWithName:@"Hot Dog" andDescription:@"Chicken"], 
                    [[Food alloc] initWithName:@"Hot Dog" andDescription:@"Veggie"], 
                    [[Food alloc] initWithName:@"Pizza" andDescription:@"Pepperonni"], 
                    [[Food alloc] initWithName:@"Pizza" andDescription:@"Pepperonni"], 
                    [[Food alloc] initWithName:@"Hot Dog" andDescription:@"Beef"], 
                    [[Food alloc] initWithName:@"Hot Dog" andDescription:@"Chicken"], 
                    [[Food alloc] initWithName:@"Hot Dog" andDescription:@"Veggie"], 
                    [[Food alloc] initWithName:@"Pizza" andDescription:@"Pepperonni"], 
                    [[Food alloc] initWithName:@"Pizza" andDescription:@"Pepperonni"], 
                    [[Food alloc] initWithName:@"Hot Dog" andDescription:@"Beef"], 
                    [[Food alloc] initWithName:@"Hot Dog" andDescription:@"Chicken"], 
                    [[Food alloc] initWithName:@"Hot Dog" andDescription:@"Veggie"], 
                    [[Food alloc] initWithName:@"Pizza" andDescription:@"Pepperonni"], 
                    [[Food alloc] initWithName:@"Pizza" andDescription:@"Pepperonni"], 
                    nil ];
    [db close];

}
 /*   
    NSLog(@"Data from ele.h file");


    /* Now here we have to write the code from the database to display the details */
    /*
    aElephant = [[NSMutableArray alloc] init];
    NSLog(@"Data base is entering");

    /*
     Here we have to set the path 
     We are creating the path for the datbase file in order to access
     */
/*  
    NSString *path  = [[NSBundle mainBundle] pathForResource:@"SampleDB" ofType:@"sqlite"];

    NSLog(@"No problem with the path");

    /* FMDatabase here is used to take the database path */
/*  
    FMDatabase *db  = [[FMDatabase alloc] initWithPath:path];

    /* Here we are opening the datase in order to access it */
/*  
    [db open];
    NSLog(@"Database Opened");

    /*
     Then the next step here is taking the database result using the sqlquery and then carrying that result into the resultset object   
     Resultset for Elephant: select * from Description where a_id=1; here description is the table, a_id is the id of Elephant it is
     the primary key in animals table
/*   */
/*  NSLog(@"NOt yet executing the query");
    FMResultSet *fResult= [db executeQuery:@"SELECT * FROM description"];
    NSLog(@"Did Execute the Query");
  //  NSLog(*fResult);

    //Now we have to take these results in to a loop and then repeteadly loop it in order to get all the data in a our Array Object

    while([fResult next])
    {
    /*  /* taking results from database to a string "eleData" */
    /*  eleData = [fResult stringForColumn:@"desc"];
        /* adding data from the string object to Array */
        //[aElephant addObject:eleData];
        /* Checking weather data has come or not */
    //  NSLog(@"The data is %@=",eleData);
    //}
    /* Closing the Database */
    //[db close];


- (void)viewDidUnload
{
    [self setSearchBar:nil];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    int rowCount;
    if(self.isFiltered)
        rowCount = filteredTableData.count;
    else
        rowCount = allTableData.count;

    return rowCount;
   // return [aElephant count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

      /*
    if(isFiltered)
        eData = [filteredTableData objectAtIndex:indexPath.row];
    else
        eData = [allTableData objectAtIndex:indexPath.row];
*/
  //  NSLog(aElephant);
 /*   NSString *eData = [aElephant objectAtIndex:indexPath.row];
    cell.textLabel.text  = eData;
    return cell;*/


    Food* food;
    if(isFiltered)
        food = [filteredTableData objectAtIndex:indexPath.row];
    else
        food = [allTableData objectAtIndex:indexPath.row];

    cell.textLabel.text = food.name;
    cell.detailTextLabel.text = food.description;


    return cell;
}

#pragma mark - Table view delegate

-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
    if(text.length == 0)
    {
        isFiltered = FALSE;
    }
    else
    {
        isFiltered = true;
        filteredTableData = [[NSMutableArray alloc] init];

        for (Food* food in allTableData)
        {
            NSRange nameRange = [food.name rangeOfString:text options:NSCaseInsensitiveSearch];
            NSRange descriptionRange = [food.description rangeOfString:text options:NSCaseInsensitiveSearch];
            if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
            {
                [filteredTableData addObject:food];
            }   
        }
    }

    [self.tableView reloadData];
}


- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    [self showDetailsForIndexPath:indexPath];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self showDetailsForIndexPath:indexPath];
}

-(void) showDetailsForIndexPath:(NSIndexPath*)indexPath
{
    [self.searchBar resignFirstResponder];
    DetailsViewController* vc = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailsViewController"];
    Food* food;

    if(isFiltered)
    {
        food = [filteredTableData objectAtIndex:indexPath.row];
    }
    else
    {
        food = [allTableData objectAtIndex:indexPath.row];
    }

    vc.food = food;
    [self.navigationController pushViewController:vc animated:true];    
}

@end

简而言之,我希望它具有sqlite数据库中的值,而不是initWithName具有静态值。 任何帮助将受到高度赞赏 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

问题是我没有回来然后正确访问数据库,并没有看到发生的变化,因为我打开我的本地数据库时,我应该在我的文档中打开iPhone模拟器中的那个。