Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8116521
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T03:51:49+00:00 2026-06-06T03:51:49+00:00

I have an SQL DB that contains Lat and Long info. I have found

  • 0

I have an SQL DB that contains Lat and Long info. I have found my current location and been able to get the distance of each location from my current location. I can get my tableview to show this distance, but know I want to sort that tableview so the closest are listed first.

My thought is I will need to add the distance to my SQL DB data, sort that some how and then display that info back to the tableview.

My thought is I would do all of this within my TableView. Looking for guidance on how to do this and if I should be doing it in the tableview.

#import "TulsaMasterViewController.h"
#import "TulsaDetailViewController.h"
#import "Bars.h"
#import "BarDatabase.h"

@implementation TulsaMasterViewController

@synthesize barArray = _barArray;
@synthesize currentLat = _currentLat;


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
currentLat = newLocation;

if (newLocation.horizontalAccuracy <= 100.0f) {
    [lm stopUpdatingLocation];
}

[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];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.barArray 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];
}

//Get the object from the array.
Bars *barObj = [self.barInfo objectAtIndex:indexPath.row];

//Set the name.
cell.textLabel.text = barObj.barName;

if (currentLat == nil) {
    cell.detailTextLabel.text = [NSString stringWithFormat:@"?"];
}else
{
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%.02f", cachedDist];
}

// Set up the cell
return cell;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:@"ShowDetails"]) {
    TulsaDetailViewController *detailViewController = [segue destinationViewController];

    detailViewController.detailItem = [self.barArray objectAtIndex:[self.tableView indexPathForSelectedRow].row];
}
}

- (void)viewDidLoad
{
[super viewDidLoad];

self.barArray = [BarDatabase database].barInfo;

lm = [[CLLocationManager alloc] init];
lm.delegate = self;
[lm startUpdatingLocation];
}

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

for (Bars *barObj in barArray) {
    NSString *strLat = barObj.Lat;
    NSString *strLong = barObj.Long;
    CLLocation *barLocation = [[CLLocation alloc] initWithLatitude:[strLat doubleValue] longitude:[strLong doubleValue]];
    CLLocationDistance distance = [currentLat distanceFromLocation:barLocation]/1000;

    [barArray addObject:[NSNumber numberWithDouble:distance]];
    NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"cachedDist" ascending:YES];
    [barArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
}

For reference the rest of my code

Bars.h

#import <Foundation/Foundation.h>

@interface Bars : NSObject {
    NSString *barName;
    NSString *barAddress;
    NSString *Lat;
    NSString *Long;
    NSString *cachedDist;
}

@property (nonatomic, copy) NSString *barName;
@property (nonatomic, copy) NSString *barAddress;
@property (nonatomic, copy) NSString *Lat;
@property (nonatomic, copy) NSString *Long;
@property (nonatomic, copy) NSString *cachedDist;

- (id)initWithName:(NSString *)name address:(NSString *)address latitude:(NSString *)latitude longitude:(NSString *)longitude distance:(NSString *)distance;

@end

Bars.m

#import "Bars.h"

@implementation Bars

@synthesize barName = _barName;
@synthesize barAddress = _barAddress;
@synthesize Lat = _Lat;
@synthesize Long = _Long;
@synthesize cachedDist = _cachedDist;

- (id)initWithName:(NSString *)name address:(NSString *)address latitude:(NSString *)latitude longitude:(NSString *)longitude distance:(NSString *)distance;
{
if ((self = [super init])) {
    self.barName = name;
    self.barAddress = address;
    self.Lat = latitude;
    self.Long = longitude;
    self.cachedDist = distance;
}
return self;
}

@end

BarDatabase.h

#import <Foundation/Foundation.h>
#import <sqlite3.h>

@interface BarDatabase : NSObject
{
    sqlite3 *_database;
}

+ (BarDatabase *)database;
- (NSMutableArray *)barInfo;

@end

BarDatabase.m

#import "BarDatabase.h"
#import "Bars.h"

@implementation BarDatabase

static BarDatabase *_database;

+ (BarDatabase *)database {
if (_database == nil) {
    _database = [[BarDatabase alloc] init];
}
return _database;
}

- (id)init {
if ((self = [super init])) {
    NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:@"TulsaBars" 
                                                         ofType:@"sqlite"];

    if (sqlite3_open([sqLiteDb UTF8String], &_database) != SQLITE_OK) {
        NSLog(@"Failed to open database!");
    }
}
return self;
}

- (void)dealloc {
sqlite3_close(_database);
}

- (NSMutableArray *)barInfo {

NSMutableArray *retval = [[NSMutableArray alloc] init];
NSString *query = @"SELECT * FROM TulsaBars";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) 
    == SQLITE_OK) {
    while (sqlite3_step(statement) == SQLITE_ROW) {
        char *nameChars = (char *) sqlite3_column_text(statement, 1);
        char *addressChars = (char *) sqlite3_column_text(statement, 2);
        char *latChars = (char *) sqlite3_column_text(statement, 8);
        char *longChars = (char *) sqlite3_column_text(statement, 9);
        NSString *name = [[NSString alloc] initWithUTF8String:nameChars];
        NSString *address = [[NSString alloc] initWithUTF8String:addressChars];
        NSString *latitude = [[NSString alloc] initWithUTF8String:latChars];
        NSString *longitude = [[NSString alloc] initWithUTF8String:longChars];

        Bars *info = [[Bars alloc]
                      initWithName:name address:address latitude:latitude longitude:longitude];                        
        [retval addObject:info];
    }
    sqlite3_finalize(statement);
}
return retval;

}
@end
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T03:51:50+00:00Added an answer on June 6, 2026 at 3:51 am

    Hrm. There should be no sorting happening inside cellForRowAtIndexPath. It’s too late in the game. If each cell is 1 bar, and the bars should be sorted by distance, I recommend achieving the sort in a lazy getter for your self.barInfo (if that’s your list of bars).

    I’m not sure what your model looks like, but if each bar object has a property for distance from whatever your reference point is, your sorting would look similar to what you have there.

    This sorting would only happen the when the first cell is loaded (that’s the “lazy” part) and then cached. So your cellForRowAtIndexPath: would just ask for the model object at it’s indexPath’s row, trusting that it is in the right order.

    I’m not sure how much of this terminology you are familiar with, so feel free to ask clarifying questions and I will iterate on the answer.

    EDIT after sharing more code:
    I think you should add a @property to the bar called something like cachedDistance, and whenever you come onscreen (viewWillAppear), iterate over the bars and set their cached distance (using similar code to what you have in cellForRow…). Then implement a getter for self.barArray: -(NSArray *)barArray which essentially returns the barArray sorted using a sortDescriptor with the name of your cached distance property as it’s key. This will simplify your cellForRow… code a lot.

    You can then extend the logic to recalculate the distances when you get location updates, perhaps only if it is a certain distance from the previous.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a SQL database that contains a field. I can get all of
I have some existing code that accepts a java.sql.ResultSet that contains info retrieved from
I have the Execute SQL Script package that contains the script to insert about
I have an SQL Server 2005 table that has a varchar(250) field which contains
I have a table which contains my ads that can be searched in sql-server-2008.
I have an Address model that contains two float fields, lat and lng .
I have a SQL query that contains a derieved table. The derived query looks
I have a SQL DB that contains multiple relational tables. There are some fields
I have a T-SQL table that contains the following columns: Date, StationCode, HDepth, and
I have a Microsoft SQL Server database that contains a data field of BIT

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.