将当前位置的距离添加到 NSMutableArray

Posted

技术标签:

【中文标题】将当前位置的距离添加到 NSMutableArray【英文标题】:Add Distance from current location to NSMutableArray 【发布时间】:2012-06-28 23:14:15 【问题描述】:

我正在尝试将我当前位置的距离加载到我的数组中,但我似乎遗漏了一些东西。我的 TableView 只显示“?”,它应该只显示我的 currentLoc 不工作,但我的 NSLog 显示正确的位置。请帮忙

更新:必须删除我的重新加载 tableView,修复“?”,但现在我只得到 0.00 公里。仍然缺少一些东西。我的 currentLoc 在 LocationManager 中是正确的,但是当我尝试计算数组中的距离时我丢失了它。

#import "AuthorViewController.h"
#import "Author.h"
#import <sqlite3.h>


@implementation AuthorViewController
@synthesize theauthors;
@synthesize currentLoc;

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

currentLoc = newLocation;

if (newLocation.horizontalAccuracy <= 100.0f) 
    [locMgr stopUpdatingLocation];

NSLog(@"Lat: %f, Long: %f", currentLoc.coordinate.latitude, currentLoc.coordinate.longitude);

[self.tableView reloadData];


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error

NSString *msg = [[NSString alloc]initWithString:@"Error obtaining location"];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:msg delegate:nil cancelButtonTitle:@"Done" otherButtonTitles:nil];
[alert show];



#pragma mark - View lifecycle

- (void)viewDidLoad

[self barList];
[super viewDidLoad];

NSLog(@"Lat2: %f, Long2: %f", currentLoc.coordinate.latitude, currentLoc.coordinate.longitude);


- (void)viewWillAppear:(BOOL)animated

[super viewWillAppear:animated];

locMgr = [[CLLocationManager alloc] init];
locMgr.delegate = self;
[locMgr startUpdatingLocation];



#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section


// Return the number of rows in the section.
return [self.theauthors 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];

int rowCount = indexPath.row;

Author *author = [self.theauthors objectAtIndex:rowCount];



cell.textLabel.text = author.barName;

if (currentLoc == nil) 
    cell.detailTextLabel.text = [NSString stringWithFormat:@"?"];
else

    cell.detailTextLabel.text = [NSString stringWithFormat:@"%.02f km", author.cachedDist];



return cell;



-(NSMutableArray *) barList
theauthors = [[NSMutableArray alloc] init];
@try 
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"TulsaBars.sqlite"];
    BOOL success = [fileMgr fileExistsAtPath:dbPath];
    if(!success)
    
        NSLog(@"Cannot locate database file '%@'.", dbPath);
    
    if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
    
        NSLog(@"An error has occured: %@", sqlite3_errmsg(db));

    


    const char *sql = "SELECT * FROM  TulsaBars";
    sqlite3_stmt *sqlStatement;
    if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
    
        NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db));
    else

        while (sqlite3_step(sqlStatement)==SQLITE_ROW) 
            Author * author = [[Author alloc] init];
            author.barName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
            author.barAddress = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
            author.barState = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 5)];
            author.barLat = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 8)];
            author.barLong = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 9)];
            author.cachedDist = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 10)];

            CLLocation *barLocation = [[CLLocation alloc] initWithLatitude:[author.barLat doubleValue] longitude:[author.barLong doubleValue]];
            CLLocationDistance distancekm = [currentLoc distanceFromLocation: barLocation]/1000;
            NSString *distanceString = [[NSString alloc] initWithFormat: @"%f", distancekm];
            author.cachedDist = distanceString;

            [theauthors addObject:author];
        
    
    sqlite3_finalize(sqlStatement);

@catch (NSException *exception) 
    NSLog(@"Problem with prepare statement:  %@", sqlite3_errmsg(db));

@finally 
    sqlite3_close(db);

    return theauthors;



@end

【问题讨论】:

【参考方案1】:

当您需要重绘表格视图中的数据时,请务必调用[tableView reloadData]

您也可以尝试此答案中列出的扩展技术:What's the best way to refresh a UITableView within a UINavigationController hierarchy

【讨论】:

谢谢,我一定是在某处删除了我的重载表。这解决了“?”问题,但现在一切都只有 0.00 公里。 您的 currentLoc ivar 是否有可能为零? 我认为这是问题所在,我只是不明白为什么。我的 Lat 和 Long 的 NSLog 显示正确,但 Lat2 和 Long2 的 NSLog 显示为 0 在渲染前是否更新了 locationManager?如果有,自上次更新后您是否调用过 reloadData? 如果不是,我一定会错过它。我认为它实际上是我加载数组的方式。

以上是关于将当前位置的距离添加到 NSMutableArray的主要内容,如果未能解决你的问题,请参考以下文章

如何将距离(以公里为单位)添加到以度和分钟为单位的位置坐标中,以获得 Java 中的新位置坐标?

在 Google Maps v2 上计算当前位置和标记之间的距离

将距离添加到 GPS 坐标

android:无法在地图上添加当前位置

从坐标数组到表格中的位置之间的距离

与 UITableView 单元格和当前位置的距离