Как отобразить данные в табличном представлении при поиске в iphone - PullRequest
0 голосов
/ 01 марта 2012

У меня есть проект, в котором есть табличное представление, текстовое поле и кнопка, и у меня есть база данных sqlite внутри проекта. В моей базе данных есть поля, такие как имя, город, штат, почтовый индекс, широта и долгота. В настоящее время я отображаю название широты и долготы, когда пользователь дает 100 в текстовом поле, то есть пользователь может дать любые метры 100 или 200, в зависимости от метров он отображает название соответствующей широты и долготы в зависимости от текущей широты и долгота. Для этого я использую следующий код,

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [resultArray count];

}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text = [resultArray objectAtIndex:indexPath.row];
    // Configure the cell...
    return cell;
}

 - (void) readDataFromDatabase{

sqlite3 *database;
info = [[NSMutableArray alloc]init];

if (sqlite3_open([[self getDBPath] UTF8String], &database) == SQLITE_OK){

    const char *sqlStatement = "select * from tourism";
    sqlite3_stmt *compiledStatement;
    if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK){
        NSLog(@"SQLITE_OK");
        while (sqlite3_step(compiledStatement) == SQLITE_ROW) {

            pID = sqlite3_column_int(compiledStatement, 0);
            pName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
            NSLog(@"%@",pName);
            pAdd = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
            NSLog(@"%@",pAdd);
            pCity = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
            NSLog(@"%@",pCity);
            pState = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
            NSLog(@"%@",pState);
            pZip = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
            NSLog(@"%@",pZip);
            pWebsite = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
            NSLog(@"%@",pWebsite);
            pCategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
            NSLog(@"%@",pCategory);
            pLat = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 8)];
            NSLog(@"%@",pLat);
            pLong = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)];
            NSLog(@"%@",pLong);
            pGeolocation = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 10)];
            NSLog(@"%@",pGeolocation);
            GreenValleyInfo *temp = [[GreenValleyInfo alloc]initWithUniqueId:(int)pID name:(NSString *)pName address:(NSString *)pAdd city:(NSString *)pCity state:(NSString *)pState zip:(NSString *)pZip website:(NSString *)pWebsite category:(NSString*)pCategory latitude:(NSString *)pLat longitude:(NSString *)pLong geolocation:(NSString *)pGeolocation];
            [info addObject:temp];
            [temp release];
        }
    }
    sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
 }

StartTest

    - (void)startTest
   {

      [resultArray removeAllObjects];
     for(int j=0;j<[info count];j++){

          GreenValleyInfo *arr = [info objectAtIndex:j];
         RADIUS = [Proxy.text intValue];

        CLLocationCoordinate2D coords[COORDS_COUNT] = {
          CLLocationCoordinate2DMake([arr.latitude floatValue], [arr.longitude floatValue]),
   };

CLLocationCoordinate2D center = CLLocationCoordinate2DMake([lat floatValue], [longt floatValue]); 
CLRegion *region = [[CLRegion alloc] initCircularRegionWithCenter:center radius:RADIUS identifier:@"Locations"];

    CLLocationCoordinate2D coord = coords[0];

    if ([region containsCoordinate:coord])
    {
        NSLog(@"location %f, %f,%@ is within %i meters of coord %f, %f", coord.latitude, coord.longitude,arr.name, RADIUS, center.latitude, center.longitude);
        [resultArray addObject:arr.name];

    }
    else 
    {
        NSLog(@"location %f, %f,%@ is not within %i meters of coord %f, %f", coord.latitude, coord.longitude,arr.name, RADIUS, center.latitude, center.longitude);    
    }
   }
 }

Но теперь мне нужно изменить метод поиска, то есть вместо того, чтобы давать метры, мне нужно указать город или почтовый индекс в текстовом поле, и оно должно отображать соответствующее имя в табличном представлении.

Заранее спасибо.

1 Ответ

0 голосов
/ 01 марта 2012

Вам необходимо отредактировать код в методе startTest. Вы получаете объект из информационного массива в массив arr. Теперь после этого вам нужно поставить галочку со значением вставленного значения поля поиска / почтового индекса со значением * arr object.

Например,

if ([arr.name isEqualTo searchField.text] || [arr.zip isEqualTo searchField.text]) 
         {
// stuff to add object to the array which is displayed in the tableview.
} 

И удалите код возврата для координатного материала или вы можете оставить комментарий для будущего использования, если это потребуется.

Надеюсь, это поможет вам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...