Search code examples
iphoneobjective-cxcodestringwithformat

Using stringWithFormat for query setup


Not entirely sure why this isn't working.

sqlite3 *db;
sqlite3_open([databasePath UTF8String], &db);
NSString *query;

NSNumber *start = (*cur_page * 50) - 50;

query = [NSString stringWithFormat:@"SELECT rest_db.rest_id, rest_db.name, prices.value FROM rest_db JOIN prices ON rest_db.rest_id = prices.table_id WHERE prices.table_name = 'rest_db'  ORDER BY rest_db.name ASC %d Limit 50;", start];

Previously, the code looked like:

sqlite3 *db;
sqlite3_open([databasePath UTF8String], &db);
NSString *query;

query = @"SELECT rest_db.rest_id, rest_db.name, prices.value FROM rest_db JOIN prices ON rest_db.rest_id = prices.table_id WHERE prices.table_name = 'rest_db'  ORDER BY rest_db.name ASC";

which worked just fine. I've tried setting start as:

int start
int *start
NSString *start

and of course I changed the "%d" accordingly for the string. All to no avail. I'm clueless at the moment. The program crashes when I hit this page now. No errors, can't get anything to write using NSLog.

I've also tried using:

[NSString alloc] initWithFormat

Any ideas? They are appreciated. Thanks.

----------------------------- EDIT ----------------------------

.h

int page_count;
int cur_page;

@property int page_count;
@property int cur_page;


.m

@synthesize page_count;
@synthesize cur_page;

int start = (cur_page * 50) - 50;

query = [NSString stringWithFormat:@"SELECT rest_db.rest_id, rest_db.name, prices.value FROM rest_db JOIN prices ON rest_db.rest_id = prices.table_id WHERE prices.table_name = 'rest_db'  ORDER BY rest_db.name ASC %d Limit 50;", start];

And now, since I did fix a typecast thanks to one of the previous suggestions, it doesn't crash the program, but shows no data from the query as start = 0. Which as I look over my code is exactly what it should equal, and if I had my sqlite statement set up correctly, I would see that I am putting it into the limit in the wrong place... -.- So the initial typecast issue was the crash and only issue, it would seem.


Solution

  • I suspect that NSNumber *start = (*cur_page * 50) - 50; is calculating an integer value and then assigning that int value to the pointer start, producing an invalid pointer. start should be declared as an int or NSInteger.