Sort TableView by distance from current location - ios

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

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.

Related

Populating Table View with JSON Data from YouTube User's Uploads - iOS

I'm struggling to populate a Table View using JSON Data from Youtube (V 2.1) which has been parsed(Logged the output in the console)
Every time I am loading the Table View Controller, nothing is populated. I have even created a 'Video' class (NSObject). I'm struggling to understand what I'm doing wrong.
The following is my code:
Video.h
#import <Foundation/Foundation.h>
#interface Video : NSObject
#property (nonatomic, strong) NSString *title;
#property (nonatomic, strong) NSString *description;
#property (nonatomic, strong) NSString *thumbnail;
#property (nonatomic, strong) NSString *uploadedDate;
#property (nonatomic, strong) NSURL *url;
// Designated Initializer
- (id) initWithTitle:(NSString *)title;
+ (id) videoWithTitle:(NSString *)title;
- (NSURL *) thumbnailURL;
- (NSString *) formattedDate;
#end
Video.m
import "Video.h"
#implementation Video
- (id) initWithTitle:(NSString *)title {
self = [super init];
if ( self ){
self.title = title;
self.thumbnail = nil;
}
return self;
}
+ (id) videoWithTitle:(NSString *)title {
return [[self alloc] initWithTitle:title];
}
- (NSURL *) thumbnailURL {
// NSLog(#"%#",[self.thumbnail class]);
return [NSURL URLWithString:self.thumbnail];
}
- (NSString *) formattedDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *tempDate = [dateFormatter dateFromString:self.uploadedDate];
[dateFormatter setDateFormat:#"EE MMM,dd"];
return [dateFormatter stringFromDate:tempDate];
}
#end
Table View Controller implementation file (the one I'm trying to populate)
#import "FilmyViewController.h"
#import "Video.h"
#interface FilmyViewController ()
#end
#implementation FilmyViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *videoURL = [NSURL URLWithString:#"http://gdata.youtube.com/feeds/api/users/OrtoForum/uploads?v=2&alt=jsonc"];
NSData *jsonData = [NSData dataWithContentsOfURL:videoURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#",dataDictionary);
self.videoArray = [NSMutableArray array];
NSArray *videosArray = [dataDictionary objectForKey:#"items"];
for (NSDictionary *vDictionary in videosArray) {
Video *video = [Video videoWithTitle:[vDictionary objectForKey:#"title"]];
video.title = [vDictionary objectForKey:#"title"];
video.description = [vDictionary objectForKey:#"author"];
video.uploadedDate = [vDictionary objectForKey:#"uploaded"];
video.url = [NSURL URLWithString:[vDictionary objectForKey:#"url"]];
[self.videoArray addObject:video];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (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 [self.videoArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
Video *video = [self.videoArray objectAtIndex:indexPath.row];
// Configure the cell...
cell.textLabel.text = video.title;
cell.textLabel.text = video.description;
return cell;
}
/*
#pragma mark - Navigation
// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
Here's the JSON which I'm trying to extract from.
I looked for similar topics but didn't get any appropriate solution for this.
Research Link-one and Link-two is what i have been trying to follow.
Please let me know if there is any better approach for this.
What am i missing here?
Solution
Changed
NSArray *videosArray = [dataDictionary objectForKey:#"items"];
to:
NSArray *videosArray = dataDictionary[#"data"][#"items"];
Change
NSArray *videosArray = [dataDictionary objectForKey:#"items"];
to
NSArray *videosArray = dataDictionary[#"data"][#"items"];
Your items array is in the second level: rootJSON -> data -> items

UITableView(with sqlite3) not update

i'm korean my english so simple
very very sorry
please help me
my application example phone book.
two View and tab bar with sqlite3 DB
first view is table view cell list, there are name is linked DB
second view save and find and delete phone book list with SQL query.
i want secondview save data and change tab update data list.
i coded [viewDidAppear] reloadData method
close the application re-open apllication is updated.
but not updated change the tap T_T please help me.
FirstViewController.h
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#interface FirstViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>
{
NSString *path;
NSString *dbName;
NSString *databasePath;
sqlite3 *contactDB;
}
#property (nonatomic) sqlite3 *contactDB_2;
#property (strong,nonatomic) IBOutlet UITableView *myTable;
#property (nonatomic,retain) NSMutableArray *quizs;
-(void)checkAndCreateDatabase;
-(void)readFromDatabase;
#end
FistViewController.m
#import "FirstViewController.h"
#import "person.h"
#implementation FirstViewController
#synthesize contactDB_2,myTable;
#synthesize quizs;
-(void)checkAndCreateDatabase{
NSFileManager *filemgr = [NSFileManager defaultManager];
if([filemgr fileExistsAtPath:databasePath] == NO){
const char *dbPath = [databasePath UTF8String];
if(sqlite3_open(dbPath,&contactDB) == SQLITE_OK){
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,ADRESS TEXT, PHONE TEXT)";
sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg);
sqlite3_close(contactDB);
}
}
}
-(void)readFromDatabase
{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if(sqlite3_open(dbpath, &contactDB)==SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT name,phone FROM contacts"];
const char *query_stmt = [querySQL UTF8String];
if(sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL)==SQLITE_OK)
{
while(sqlite3_step(statement)==SQLITE_ROW){
NSString* nameField = [[NSString alloc]initWithUTF8String:(const char*)sqlite3_column_text(statement, 0)];
NSString* phoneField = [[NSString alloc]initWithUTF8String:(const char*)sqlite3_column_text(statement, 1)];
person *persons = [person alloc];
[persons setName:nameField];
[persons setPhone:phoneField];
[quizs addObject:persons];
}
sqlite3_finalize(statement);
[myTable reloadData];
}
sqlite3_close(contactDB);
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"전화번호목록", #"전화번호목록");
self.tabBarItem.image = [UIImage imageNamed:#"first"];
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
pragma mark - View lifecycle
- (void)viewDidLoad
{
dbName = #"contacts2.db";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:dbName];
[self checkAndCreateDatabase];
quizs = [[NSMutableArray alloc] initWithCapacity:100];
[self readFromDatabase];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[myTable delegate];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[quizs removeAllObjects];
[self checkAndCreateDatabase];
[self readFromDatabase];
[myTable reloadData];
}
- (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 != UIInterfaceOrientationPortraitUpsideDown);
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return quizs.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];
}
person *p = [quizs objectAtIndex:indexPath.row];
NSString *str = [[NSString alloc]initWithFormat:#"%# %#",p.name,p.phone];
cell.textLabel.text = str;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = indexPath.row;
NSString *temp = [[NSString alloc]initWithFormat:#"%d번쨰꺼 선택해뜸",row+1];
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:#"터치" message:temp delegate:self cancelButtonTitle:nil otherButtonTitles:#"확인", nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
I want change the tab and update cell list.
Actually you can not insert the data in database in background .So until all data are inserted you have to keep application alive. If all data are saved successfully then please write reloadData code in ViewWillAppear.

Search Bar and Search Display, unrecognized selector sent to instance

I have a problem with a searchBar, i get an error unrecognized selector.
2013-02-11 14:48:27.211 Scores (FREE)[13946:c07] test ijsid
CONTAINS[cd] "A" 2013-02-11 14:48:27.213 Scores (FREE)[13946:c07] test
(
Axel,
"Double Axel",
"Triple Axel",
"Quad Axel" ) 2013-02-11 14:48:27.213 Scores (FREE)[13946:c07] -[SingleElements isEqualToString:]: unrecognized selector sent to instance 0x755a5f0 2013-02-11 14:48:27.214 Scores (FREE)[13946:c07]
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SingleElements
isEqualToString:]: unrecognized selector sent to instance 0x755a5f0'
* First throw call stack: (0x209f012 0x11ace7e 0x212a4bd 0x208ebbc 0x208e94e 0x249e9f 0x24a064 0x2ae4 0x1ab8fb 0x1ab9cf 0x1941bb 0x192872
0x19d701 0x1a5d5d 0x1ade04 0x3d55f5 0x3d809e 0x327cc5 0x11c0705
0xf4213 0x1b5c7e 0x1b5310 0x1c213c 0x1cc5a6 0xc6d4f9 0x20f90c5
0x2053efa 0xba1bb2 0x38a39de 0x29f11da 0x2e2adfc 0x2e2dbf8 0x387e612
0x387e74a 0x387eec0 0x387ecb8 0x387e204 0x2c6c22b 0x2c6c193 0x3850e96
0x387d4cc 0x2e28136 0x2e273c6 0x2e5a980 0x34b67fd 0x2e51576 0x2e526da
0x2e5072e 0x34b4eaa 0x2e6aaf1 0x2e5a72a 0x2e2e6ae 0x2a2d62b 0x11c06b0
0x3899810 0x2a6c1a4 0x2a6e2ff 0x2b20b4 0x274aef 0x275e58 0x2749fe
0x27ed29 0x101ddb 0x1ff7f5 0x1ff7f5 0x1ff7f5 0x1ff7f5 0x1ff7f5
0x1ff7f5 0x1ff7f5 0x1ff7f5 0x1ff7f5 0x101e35 0x101806 0x101beb 0xf3698
0x1ffadf9 0x1ffaad0 0x2014bf5 0x2014962 0x2045bb6 0x2044f44 0x2044e1b
0x1ff97e3 0x1ff9668 0xf0ffc 0x1f8d 0x1eb5) libc++abi.dylib: terminate
called throwing an exception
(lldb) po 0x755a5f0 $0 = 123053552 Axel
.h
#interface SingleElementsVC : UITableViewController{
NSMutableArray *thesingleelementslist;
sqlite3 * db;
UISearchDisplayController *searchDisplayController;
UISearchDisplayController *searchBar;
NSMutableArray *searchResults;
}
#property(nonatomic,retain) NSMutableArray *thesingleelementslist;
#property(nonatomic, strong)SingleElementsDetailView *details;
-(NSMutableArray *) singleElementsList;
#property (nonatomic, retain) IBOutlet UISearchDisplayController *searchDisplayController;
#property (nonatomic, retain) IBOutlet UISearchDisplayController *searchBar;
#property (nonatomic, copy) NSMutableArray *searchResults;
#end
.m
#interface SingleElementsVC ()
#end
#implementation SingleElementsVC
#synthesize thesingleelementslist;
#synthesize searchDisplayController;
#synthesize searchBar;
#synthesize searchResults;
- (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];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
[self singleElementsList];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (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 the number of sections.
return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *sectionHeader = nil;
sectionHeader = #"Scale Of Values For Single";
return sectionHeader;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
NSInteger rows = 0;
if ([tableView
isEqual:self.searchDisplayController.searchResultsTableView]){
rows = [self.searchResults count];
}
else{
rows = [self.thesingleelementslist count];
}
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"SingleElementsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]){
cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
}
else{
SingleElements *singleElements = [self.thesingleelementslist objectAtIndex:indexPath.row];
cell.textLabel.text = singleElements.ijsid;
NSString *singleElementsDescriptionAndBase = [NSString stringWithFormat:#"%# (%#)",singleElements.description, singleElements.base];
cell.detailTextLabel.text = singleElementsDescriptionAndBase;
}
return cell;
}
-(NSMutableArray *) singleElementsList{
thesingleelementslist = [[NSMutableArray alloc] initWithCapacity:10];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"ElementsDb.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: %s", sqlite3_errmsg(db));
}
const char *sql = "SELECT * FROM single";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}else{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
SingleElements * singleElements = [[SingleElements alloc] init];
singleElements.group = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
singleElements.ijsid = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
singleElements.description = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,3)];
singleElements.plus3 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,4)];
singleElements.plus2 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,5)];
singleElements.plus1 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,6)];
singleElements.base = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,7)];
singleElements.baseur = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,8)];
singleElements.minus1 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,9)];
singleElements.minus2 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,10)];
singleElements.minus3 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,11)];
singleElements.goeplus3 = [singleElements.plus3 decimalNumberByAdding:singleElements.base];
singleElements.goeplus2 = [singleElements.plus2 decimalNumberByAdding:singleElements.base];
singleElements.goeplus1 = [singleElements.plus1 decimalNumberByAdding:singleElements.base];
singleElements.goeminus1 = [singleElements.minus1 decimalNumberByAdding:singleElements.base];
singleElements.goeminus2 = [singleElements.minus2 decimalNumberByAdding:singleElements.base];
singleElements.goeminus3 = [singleElements.minus3 decimalNumberByAdding:singleElements.base];
[thesingleelementslist addObject:singleElements];
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}
#finally {
sqlite3_close(db);
return thesingleelementslist;
}
}
- (void)filterContentForSearchText:(NSString*)searchText
scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"ijsid contains[cd] %#",
searchText];
self.searchResults = [NSMutableArray arrayWithArray:[self.thesingleelementslist filteredArrayUsingPredicate:resultPredicate]];
NSLog(#"test %#", searchResults);
}
#pragma mark - UISearchDisplayController delegate methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//if ([[segue identifier] isEqualToString:#"showDetail"]) {
SingleElementsDetailView *detailViewController = [segue destinationViewController];
SingleElements *singleElements = [[SingleElements alloc]init];
detailViewController.singleElements = [self.singleElementsList objectAtIndex:[self.tableView indexPathForSelectedRow].row];
singleElements = [self.singleElementsList objectAtIndex:[self.tableView indexPathForSelectedRow].row];
NSLog(#"test %#", singleElements.ijsid);
NSLog(#"test %#", singleElements.description);
NSLog(#"test %#", singleElements.goeplus3);
NSLog(#"test %#", singleElements.goeplus2);
NSLog(#"test %#", singleElements.goeplus1);
NSLog(#"test %#", singleElements.base);
NSLog(#"test %#", singleElements.goeminus1);
NSLog(#"test %#", singleElements.goeminus2);
NSLog(#"test %#", singleElements.goeminus3);
//}
}
#end
Class SingleElements.h
#interface SingleElements : NSObject{
NSString *group;
NSString *ijsid;
NSString *description;
NSDecimalNumber *plus3;
NSDecimalNumber *plus2;
NSDecimalNumber *plus1;
NSDecimalNumber *base;
NSDecimalNumber *baseur;
NSDecimalNumber *minus1;
NSDecimalNumber *minus2;
NSDecimalNumber *minus3;
NSDecimalNumber *goeplus3;
NSDecimalNumber *goeplus2;
NSDecimalNumber *goeplus1;
NSDecimalNumber *goeminus1;
NSDecimalNumber *goeminus2;
NSDecimalNumber *goeminus3;
}
#property(nonatomic,copy) NSString *group;
#property(nonatomic,copy) NSString *ijsid;
#property(nonatomic,copy) NSString *description;
#property(nonatomic,copy) NSDecimalNumber *plus3;
#property(nonatomic,copy) NSDecimalNumber *plus2;
#property(nonatomic,copy) NSDecimalNumber *plus1;
#property(nonatomic,copy) NSDecimalNumber *base;
#property(nonatomic,copy) NSDecimalNumber *baseur;
#property(nonatomic,copy) NSDecimalNumber *minus1;
#property(nonatomic,copy) NSDecimalNumber *minus2;
#property(nonatomic,copy) NSDecimalNumber *minus3;
#property(nonatomic,copy) NSDecimalNumber *goeplus3;
#property(nonatomic,copy) NSDecimalNumber *goeplus2;
#property(nonatomic,copy) NSDecimalNumber *goeplus1;
#property(nonatomic,copy) NSDecimalNumber *goeminus1;
#property(nonatomic,copy) NSDecimalNumber *goeminus2;
#property(nonatomic,copy) NSDecimalNumber *goeminus3;
#end
Any help are welcome, thanks.
Is SingleElements subclass of NSString ??
My guess would be isEqualToString is not available for SingleElements.
Can you post code for SingleElements class?
EDIT:
From your updated question I can see that it's a subclass of NSObject which hasn't any idea with what isEqualToString has to do with.
For getting to the line of crash (which you will not have any clue, If I guessed it right), Try to do as following:
Go to the breakpoints navigator in the left pane.
Click the plus button at the bottom of the screen.
Choose Add Exception Breakpoint
In the bubble that pops up choose Objective-C in the Exception field.
Execute the program again
Now, Try to have that exception again. XCode will bring you to that line before crashing.
Then, Post that line here. May be then, We can go for the solution.

How to setup a MapViewController as Datasource to a TableViewController for displaying distance in cells

My app has a tabbarcontroller with a UIViewController (FirstViewController-calling it mapVC) with a mapview and a UITableViewController (SecondViewController-calling it tableVC). The app fetches data from web and puts it into CD-db and each VC executes a fetch to the db. Each entity is named Holiday (dont ask) and it has a lat and long property.
Here is the UITabBarController subclass which attempts to set the mapVC as datasource to tableVC:
- (void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view.
FirstViewController *mapVC;
SecondViewController *tableVC;
for(UIViewController *anyVC in self.viewControllers)
{
if([anyVC.class isKindOfClass:[SecondViewController class]]){
tableVC = (SecondViewController *)anyVC;
} else if ([anyVC.class isKindOfClass:[FirstViewController class]]){
mapVC = (FirstViewController *)anyVC;
}
}
tableVC.tableView.dataSource = mapVC;
tableVC.tableView.delegate = mapVC;
}
Here are the relevant parts of mapVC:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "SecondViewController.h"
#define METERS_PER_MILE 2609.344
#interface FirstViewController : UIViewController <MKMapViewDelegate, UITableViewDataSource, UITableViewDelegate>{
BOOL _doneInitialZoom;
}
#property (strong, nonatomic) IBOutlet MKMapView *_mapView;
#property (strong, nonatomic) IBOutlet UIBarButtonItem *refreshButton;
#property (nonatomic, strong) NSString *entityName;
#property (strong, nonatomic) CLLocation *userLocation;
- (IBAction)refreshTapped:(id)sender;
-(void)showDetailView;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
#end
and its implementation:
#import "FirstViewController.h"
#import "Holiday.h"
#import "MyLocation.h"
#import "SDCoreDataController.h"
#import "MyTabBarController.h"
#import "TableViewCell.h"
- (void)loadRecordsFromCoreData {
[self.managedObjectContext performBlockAndWait:^{
[self.managedObjectContext reset];
NSError *error = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:self.entityName];
[request setSortDescriptors:[NSArray arrayWithObject:
[NSSortDescriptor sortDescriptorWithKey:#"date" ascending:YES]]];
self.farSiman = [self.managedObjectContext executeFetchRequest:request error:&error];
}];
NSLog(#"self.farSiman on launch = %#", self.farSiman);
}
- (void)plotStorePositions:(NSString *)responseString {
for (id<MKAnnotation> annotation in _mapView.annotations) {
[_mapView removeAnnotation:annotation];
}
NSLog(#"Dictionary is %#", self.farSiman);
for (Holiday * holidayObject in self.farSiman) {
NSString * latitude = holidayObject.latitude;
NSString * longitude = holidayObject.longitude;
NSString * storeDescription = holidayObject.name;
NSString * address = holidayObject.address;
CLLocationCoordinate2D coordinate;
coordinate.latitude = latitude.doubleValue;
coordinate.longitude = longitude.doubleValue;
MyLocation *annotation = [[MyLocation alloc] initWithName:storeDescription address:address coordinate:coordinate distance:0];
//
CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
//[(MyLocation*)[view annotation] coordinate].latitude longitude:[(MyLocation*)[view annotation] coordinate].longitude]];
self.userLocation = [[CLLocation alloc] initWithLatitude:self._mapView.userLocation.coordinate.latitude longitude:self._mapView.userLocation.coordinate.longitude];
NSLog(#"PLOT>>userLocation is %#", userLocation);
CLLocationDistance calculatedDistance = [pinLocation distanceFromLocation:self.userLocation];
annotation.distance = calculatedDistance/1000;
NSLog(#"PLOT>>Distance to pin %4.0f", annotation.distance);
//
[_mapView addAnnotation:annotation];
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self.farSiman count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = nil;
// Check to see whether the normal table or search results table is being displayed and set the Candy object from the appropriate array
NSLog(#"Already in CFRAIP");
static NSString *CellIdentifier = #"HolidayCell";
if (cell == nil) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
//cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
}
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Holiday *holiday = [self.farSiman objectAtIndex:indexPath.row];
cell.nameLabel.text = holiday.name;
//cell.dateLabel.text = holiday.latitude;
cell.dateLabel.text = [[self calculateDistanceForLat:[holiday.latitude doubleValue] Long:[holiday.longitude doubleValue]] stringValue];
if (holiday.image != nil) {
UIImage *image = [UIImage imageWithData:holiday.image];
cell.imageView.image = image;
} else {
cell.imageView.image = nil;
}
return cell;
}
// Add new method above refreshTapped
- (NSNumber*)calculateDistanceForLat:(double)lati Long:(double)longi {
double distancia;
CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude:lati longitude:longi];
CLLocationDistance calculatedDistance = [pinLocation distanceFromLocation:self.userLocation];
//test locations
NSLog(#"pinLocations is %#, userLocation is %#", pinLocation, self.userLocation);
distancia = calculatedDistance/1000;
return [NSNumber numberWithDouble:distancia];
}
The plotStoreLocations method is the only method call from a UIButton in the mapVC toolbar.
As for tableVC (SecondViewController)
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface SecondViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate>
#property (nonatomic, strong) NSArray *dates;
#property (nonatomic, strong) NSString *entityName;
#property (strong, nonatomic) IBOutlet UIBarButtonItem *refreshButton;
#property (strong,nonatomic) NSMutableArray *filteredResultsArray;
#property (strong,nonatomic) IBOutlet UISearchBar *resultsSearchBar;
#property (strong, nonatomic) CLLocation *userLocation;
- (IBAction)refreshButtonTouched:(id)sender;
And its implementation:
- (void)loadRecordsFromCoreData {
[self.managedObjectContext performBlockAndWait:^{
[self.managedObjectContext reset];
NSError *error = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:self.entityName];
[request setSortDescriptors:[NSArray arrayWithObject:
[NSSortDescriptor sortDescriptorWithKey:#"date" ascending:YES]]];
self.dates = [self.managedObjectContext executeFetchRequest:request error:&error];
NSLog(#"self.dates==%#",self.dates);
}];
}
#pragma mark - Table view data source
- (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.
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredResultsArray count];
} else {
return [self.dates count];
}
//return [self.dates count];
}
// Add new method above refreshTapped
- (NSNumber*)calculateDistanceForLat:(double)lati Long:(double)longi {
double distancia;
CLLocation *pinLocation = [[CLLocation alloc] initWithLatitude:lati longitude:longi];
CLLocationDistance calculatedDistance = [pinLocation distanceFromLocation:self.userLocation];
//test locations
NSLog(#"pinLocations is %#, userLocation is %#", pinLocation, self.userLocation);
distancia = calculatedDistance/1000;
return [NSNumber numberWithDouble:distancia];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = nil;
if (tableView == self.searchDisplayController.searchResultsTableView) {
static NSString *CellIdentifier = #"HolidayCell";
if (cell == nil) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Holiday *holiday = [filteredResultsArray objectAtIndex:indexPath.row];
NSLog(#"the holiday is %#", holiday.name);
cell.nameLabel.text = holiday.name;
} else {
static NSString *CellIdentifier = #"HolidayCell";
if (cell == nil) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Holiday *holiday = [self.dates objectAtIndex:indexPath.row];
cell.nameLabel.text = holiday.name;
cell.dateLabel.text = [[self calculateDistanceForLat:[holiday.latitude doubleValue] Long:[holiday.longitude doubleValue]] stringValue];
if (holiday.image != nil) {
UIImage *image = [UIImage imageWithData:holiday.image];
cell.imageView.image = image;
} else {
cell.imageView.image = nil;
}
}
return cell;
}
Finally MyLocation:
import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface MyLocation : NSObject <MKAnnotation> {
NSString *_name;
NSString *_address;
CLLocationCoordinate2D _coordinate;
}
#property (copy) NSString *name;
#property (copy) NSString *address;
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
#property (assign) float distance;
- (id)initWithName:(NSString*)name address:(NSString*)address coordinate:(CLLocationCoordinate2D)coordinate distance:(float)distance;
#end
#import "MyLocation.h"
#implementation MyLocation
#synthesize name = _name;
#synthesize address = _address;
#synthesize coordinate = _coordinate;
#synthesize distance = _distance;
- (id)initWithName:(NSString*)name address:(NSString*)address coordinate:(CLLocationCoordinate2D)coordinate distance:(float)distance{
if ((self = [super init])) {
_name = [name copy];
_address = [address copy];
_coordinate = coordinate;
_distance = distance;
}
return self;
}
- (NSString *)title {
if ([_name isKindOfClass:[NSNull class]])
return #"Unknown charge";
else
return _name;
}
- (NSString *)subtitle {
return [NSString stringWithFormat:#"A %0.2f Kms", _distance];
//return _address;
}
Specific Questions:
1) If I added the cFRAIP (noris & nosit) method in mapVC (the new datasource) do I need to remove it from tableVC?
2) If I remove cFRAIP and the other 2 (noris and nosit) methods from tableVC, it crashes because there is no datasource. So the tabbarcontroller assignment of datasource doesnt seem to be working.
3) Finally if I have to remove cFRAIP from tableVC, I will lose my ability to UISearchBar the tableview. Or am I wrong?
When I run the app, the mapVC is the selected vc. The UIButton in the toolbar that calls plotStoreLocations in mapVC is greyed out until the web fetch finishes. At this point the console logs the self.farsiman locations which are Holiday entities. And I can see all the entities log into the console.
When I click the plot button, the userLocation is logged correctly as specified in the plotStorePositions and the distance value for each annotation is correct. So the distance for each MKAnnotation is calculated correctly.
When I switch to the tableVC tab, the new self.dates array is logged in the console (because I currently have the tableVC do another CD-db fetch. And I get this for each pin location:
Already in CFRAIP pinLocations is <+15.50288611,-88.02716389> +/-
0.00m (speed -1.00 mps / course -1.00) # 1/24/13, 8:20:39 PM Central Standard Time, userLocation is (null)
which is called from the calculateDistanceForLat which is called by the CFRAIP. And every distance in the cell detail is -0.001.
You definitely need to make mapVC the datasource and delegate. If UITableViewController isn't letting you assign it to something other that itself you might want to consider using a regular UIViewController and drop a UITableView on to it. If you set it up as a property called tableview the code in tabbarcontroller that does tableVC.tableView.dataSource = mapVC; will still work.
Yes you can and should remove all tableview delegate and datasource code from your tableVC, if it is calling those then it isn't calling the ones in the mapVC which is what you want.
It's probably giving you the wrong distance because tableVC doesn't have the user's location to measure from. Another good reason for having the table datasource attached to the map.

Pass CLLocation data to UITableView

I'm trying to load my UITableView with distance from current location. I'm taking small steps in just trying to get the Latitude to load into the UITableView. My NSLog is reading the correct Lat/Long, but my Table is reading 0.000. At this point I'm not sure if it's my memory management or something else. Please help.
My ViewController.h
#import <UIKit/UIKit.h>
#import "CoreLocation/CoreLocation.h"
#interface TulsaMasterViewController : UITableViewController <CLLocationManagerDelegate>
{
NSArray *_barInfo;
CLLocationManager *lm;
NSString *currentLat;
}
#property (nonatomic, strong) NSArray *barInfo;
#property (nonatomic, strong) NSString *currentLat;
#end
My ViewController.m
#import "TulsaMasterViewController.h"
#import "TulsaDetailViewController.h"
#import "Bars.h"
#import "BarDatabase.h"
#implementation TulsaMasterViewController
#synthesize barInfo = _barInfo;
#synthesize currentLat = _currentLat;
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"%f", newLocation.coordinate.latitude);
NSLog(#"%f", newLocation.coordinate.longitude);
currentLat = [NSString stringWithFormat:#"%f", newLocation.coordinate.latitude];
}
- (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.barInfo 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 coffename.
cell.textLabel.text = barObj.barName;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%f", currentLat];
// 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.barInfo objectAtIndex:[self.tableView indexPathForSelectedRow].row];
}
}
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.barInfo = [BarDatabase database].barInfo;
lm = [[CLLocationManager alloc] init];
lm.delegate = self;
[lm startUpdatingLocation];
}
#end
You need to update your tableview when the didUpdateToLocation method is called

Resources