Distance

List the area codes within five miles of the selected area code, in order of decreasing proximity.

Source code in Distance.zip

  1. main.m
  2. Class DistanceAppDelegate
  3. Class Model
  4. Class ViewController
  5. Class View

The model

The Model object opens the SQLite database, reads from it, and closes it. Other than init and dealloc, it has only one method, getZipCodes:. This method executes the following two statements of SQL with sqlite3_prepare_v2 and sqlite3_step. Assume the zipcode is 10003, whose latitude and longitude are 40.731253° N 73.989223° W.

select latitude, longitude from zipcodes where zipcode == 10003;

select *, distance(latitude, longitude, 40.731253, -73.989223) as d
	from zipcodes
	where d < 5
	order by d;

If the sqlite3_column_text contains Unicode characters, you must copy it into an NSString like this:

	NSString *subtitle = [NSString stringWithUTF8String:
		sqlite3_column_text(statement, 1)];

Add a function to SQLite

The SQLite language has many functions: max, min, etc. But it does not know about latitude and longitude, and does not have any function named distance. The model adds a four-argument distance function to the language by calling sqlite3_create_function after it opens the database.

Create the project

Add the SQLite database file zipcodes.db to your project. We created this file by .importing the csv file into sqlite3.

Model.h mentions the data type sqlite3, so it must #import the header file "/usr/include/sqlite3.h". Model.m mentions class CLLocation, so it must #import <CoreLocation/CoreLocation.h>

Project → Edit Active Target "Distance"
General → Linked Libraries

Add libsqlite3.dylib and CoreLocation.framework.