How to dynamically sorting an NSMutableArray in Objective-C? - iphone

I am retrieving rows from SQLite table, then dynamically creating an object, and then adding the object to an NSMutableArray. My problem is that I am unable to figure out a way to dynamically sort the objects in the array based on the distance attribute (which is a double), as I am adding each object to the NSMutableArray in a for-loop, from smallest to largest.
My relevant code looks like this:
sqlite3 *database;
//Init the restaurant array
restaurants = [[NSMutableArray alloc] init];
CLLocation *firstLocation = [[[CLLocation alloc] initWithLatitude:userLatitude longitude:userLongitude] autorelease];
//Open the database from the users filesystem
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
//setup the SQL statement and compile it for faster access
const char *sqlStatement = "select * from restaurant";
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
//loop through the results and add them to the feeds array
while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
//read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aAddress = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aCity = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *aProvinceState = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *aPostalZipCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *aCountry = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *aPhoneNumber = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
NSString *aHours = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 8)];
double aLat = sqlite3_column_double(compiledStatement, 9);
double aLon = sqlite3_column_double(compiledStatement, 10);
CLLocation *secondLocation = [[[CLLocation alloc] initWithLatitude:aLat longitude:aLon] autorelease];
CLLocationDistance restDistance = [secondLocation distanceFromLocation:firstLocation];
CLLocationDistance distanceKm = restDistance / 1000.0;
NSString *aDist = [[NSString alloc] initWithFormat: #"%f", distanceKm];
Restaurant *restaurant = [[Restaurant alloc] initWithName:aName address:aAddress city:aCity provinceState:aProvinceState postalZipCode:aPostalZipCode country:aCountry phoneNumber:aPhoneNumber hours:aHours latitude:aLat longitude:aLon distance:aDist];
//add the restaurant object to the restaurant array
[restaurants addObject:restaurant];
[restaurant release];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
Once this function has finished its course, the restaurants array should be a sorted array containing restaurant objects that are in order of nearest (smallest distance double value) to furthest (largest distance double value).

Use NSMutableArray's sortUsingSelector to call a comparison function on your Restaurant object.
#implementation Restaurant
- (double) distance { return _distance; }
- (NSComparisonResult) compareDistance:(Restaurant *) iRHS {
double lhs, rhs;
lhs = [self distance];
rhs = [iRHS distance];
if ( lhs < rhs ) return NSOrderedAscending;
if ( lhs > rhs ) return NSOrderedDescending;
return NSOrderedSame;
}
#end
...
[restaurants sortUsingSelector: #selector(compareDistance:)];

Related

How to fetch All data of the columns in the table

this is my code...
i want to fetch all the quotes data that have 320 quote but it only fetch the first one quote. please help me
-(NSMutableArray *)getAllQuotesData
{
NSMutableArray *quotesArray = [[NSMutableArray alloc] init];
NSString *sqlStr = [NSString stringWithFormat:#"SELECT quote FROM quotes"];
sqlite3_stmt *ReturnStatement = (sqlite3_stmt *) [self getStatement:sqlStr];
while (sqlite3_step(ReturnStatement)==SQLITE_ROW)
{
#try
{
QuotesDC *myQuote = [[QuotesDC alloc] init];
NSString *user_id = [NSString stringWithUTF8String:(char
*)sqlite3_column_text(ReturnStatement,0)];
NSString *category = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,1)];
NSString *subcategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,2)];
NSString *quote = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,0)];
NSString *star = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,4)];
myQuote.userid = [user_id integerValue];
myQuote.category = category;
myQuote.subcategory = subcategory;
myQuote.quote = quote;
myQuote.star = star;
[quotesArray addObject:myQuote];
NSLog(#"%u", quotesArray.count);
}
#catch (NSException *ept) {
NSLog(#"Exception in %s, Reason: %#", __PRETTY_FUNCTION__, [ept reason]);
}
return quotesArray;
}
}
nothing wrong with your code just do one thing return dataArray will be outside of the loop , you will load all quotes like this, accept my answer thanks
-(NSMutableArray *)getAllQuotesData
{
NSMutableArray *quotesArray = [[NSMutableArray alloc] init];
NSString *sqlStr = [NSString stringWithFormat:#"SELECT quote FROM quotes"];
sqlite3_stmt *ReturnStatement = (sqlite3_stmt *) [self getStatement:sqlStr];
while (sqlite3_step(ReturnStatement)==SQLITE_ROW)
{
#try
{
QuotesDC *myQuote = [[QuotesDC alloc] init];
NSString *user_id = [NSString stringWithUTF8String:(char
*)sqlite3_column_text(ReturnStatement,0)];
NSString *category = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,1)];
NSString *subcategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,2)];
NSString *quote = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,0)];
NSString *star = [NSString stringWithUTF8String:(char *)sqlite3_column_text(ReturnStatement,4)];
myQuote.userid = [user_id integerValue];
myQuote.category = category;
myQuote.subcategory = subcategory;
myQuote.quote = quote;
myQuote.star = star;
[quotesArray addObject:myQuote];
NSLog(#"%u", quotesArray.count);
}
#catch (NSException *ept) {
NSLog(#"Exception in %s, Reason: %#", __PRETTY_FUNCTION__, [ept reason]);
}
}
return quotesArray;
}
Replace your query string with this
NSString *sqlStr = [NSString stringWithFormat:#"SELECT * FROM quotes WHERE quote=320"];
Use this code,this may help you
-(void)retrivequoteFromDB
{
NSMutableArray * quoteArray=[[NSMutableArray alloc]init];
sqlite3 *sqliteDB;
sqlite3_stmt *compiledStatement = NULL;
if(sqlite3_open([databasePath UTF8String], &sqliteDB)==SQLITE_OK)
{
NSString *sql=#"SELECT quote FROM quotes";
const char *sqlC=[sql UTF8String];
if(sqlite3_prepare(sqliteDB, sqlC, -1, &compiledStatement, NULL)==SQLITE_OK)
{
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
NSString *quote = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
[quoteArray addObject:quote];
}
}
sqlite3_reset(compiledStatement);
}
sqlite3_finalize(compiledStatement);
}
try like this once check your data base table 320 records placed or not if present then it'l gives ll the data.
SELECT quote FROM quotes //it'l gives only quote columnvalues from quotes table.
if you want to get all the data then use asterisk '*' symbol in the place of quote.
otherwise try like this,
SELECT quote FROM quotes limit 320 //it'l gives top 320 records
once read this one you'l found the problem. select Query

how to select unique values from sqlite table in iphone

I have data in my sqlite table like the following
here is the my table description and fields
coffeeID;
category;
sub_Category;
content_Type;
content_Title;
content_Description;
content_Id;
publisher;
content_Source;
update_date_time;
and here is the code where i am now getting all values but i want unique values.
const char *sql = "select * from category";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
coffeeObj.category=sqlite3_column_int(selectstmt,1);
coffeeObj.sub_Category = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
coffeeObj.content_Type = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
coffeeObj.content_Title = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt,4)];
coffeeObj.publisher = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
coffeeObj.content_Description = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 6)];
coffeeObj.content_Id = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 7)];
coffeeObj.content_Source = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 8)];
int count=[appDelegate.coffeeArray count];
NSLog(#"count is beofore getting values %d",count);
[appDelegate.coffeeArray addObject:coffeeObj];
int countone=[appDelegate.coffeeArray count];
NSLog(#"count is after getting values %d",countone);
[coffeeObj release];
}
}
}
I want that if it has two same sub categories then it may show only one like mean only unique records not the categories with same name repeated.
You can use Group by in SQL Query
"Select * From category GROUP BY category"
You can group by any column

How to get int data from iphone sqlite data base

I am getting data from iphone sqlite like this. I have 6 records in the table.
My table has fields responses_Id, participant_Id, answer_option, answer_text, update_date_time only all are varchar fields except responses_Id and participant_Id)
+ (void) getInitialDataToDisplay:(NSString *)dbPath {
CereniaAppDelegate *appDelegate = (CereniaAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select * from survey_question_responses";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
coffeeObj.participant_Id=(This is integerin table)
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
NSString*test=coffeeObj.answer_option;
[appDelegate.coffeeArray addObject:coffeeObj];
int count=[appDelegate.coffeeArray count];
NSLog(test);
NSLog(#"count is %d",count);
[coffeeObj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
When I NSlog data it does not show any things.
Look into the SQLite Documentation. All result values from queries are defined there.
You can use sqlite3_column_int for Integers similar to sqlite3_column_text for Text
NSNumber *primaryKey = [NSNumber numberWithInt:(int)sqlite3_column_int(selectstmt, 0)];
while(sqlite3_step(selectAllStmt) == SQLITE_ROW)
{
NSLog(#"record found");
char *temp = (char *)sqlite3_column_text(selectAllStmt, 0);
if (temp!=nil) {
intId=[[NSString stringWithUTF8String:temp] intValue];
}
temp =NULL;
// [pool release];
}
+ (void) getInitialDataToDisplay:(NSString *)dbPath {
CereniaAppDelegate *appDelegate = (CereniaAppDelegate *)[[UIApplication sharedApplication] delegate];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = "select * from survey_question_responses";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSInteger primaryKey;
NSInteger intparticipant_Id;
char *temp = (char *)sqlite3_column_text(selectstmt, 0);
if (temp!=nil) {
primaryKey=[[NSString stringWithUTF8String:temp] intValue];
}
temp =NULL;
Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey];
temp = (char *)sqlite3_column_text(selectstmt, 1);
if (temp!=nil) {
intparticipant_Id=[[NSString stringWithUTF8String:temp] intValue];
}
temp =NULL;
coffeeObj.participant_Id=intparticipant_Id;
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
coffeeObj.answer_option = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
NSString*test=coffeeObj.answer_option;
[appDelegate.coffeeArray addObject:coffeeObj];
int count=[appDelegate.coffeeArray count];
NSLog(test);
NSLog(#"count is %d",count);
[coffeeObj release];
}
}
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
Note:- char *temp = (char *)sqlite3_column_text(selectAllStmt, 0);
if(temp != NULL)
str = [NSString stringWithUTF8String:temp];
else
str = #"";
temp =NULL;
If you want to take integer then you can do type casting "str = [NSString stringWithUTF8String:temp];" here......

SQLite and OBJ-C DB clear when launch application

I've a SQLite db on this position
/Users/software/Library/Application Support/iPhone Simulator/5.0/Applications/723EEE91-CB9D-4A27-8492-D61E127E72B7/myAPP.app/localDB.sqlite
No problems on write, delete or read data.
For example if I write on DB and close application, I find data in my DB, but if I restart the app my DB will clear. Can someone tell me why?
This is an example of a DB instance
SQLiteUtilities *db = [[SQLiteUtilities alloc]init:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"localDB.sqlite"]];
[db loadValuesFromQuery:#"SELECT * FROM categories;"];
for (int i = 0; i < [db getSize]; i++) {
NSLog(#"-- %#", [db objectAtIndex:i]);
}
[db release];
-(void)loadValuesFromQuery:(NSString *)query {
GenericRecord *record = [[[GenericRecord alloc]init] autorelease];
if (sqlite3_open([pathDB UTF8String], &database) == SQLITE_OK) {
// query che ricava i valori
const char *sql = (const char *) [query UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
// ricaviamo i valori letti dalla query
record.uniqueID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
record.superID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
record.subSuperID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
record.title = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)];
record.description = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 5)];
record.price = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 6)];
record.note = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 7)];
record.pictureURL = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 8)];
record.catName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 9)];
record.subCatName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 10)];
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstmt, 11) length:sqlite3_column_bytes(selectstmt, 11)];
if(data) record.imageBig = [UIImage imageWithData:data];
[self.list addObject:record];
}
}
}
sqlite3_close(database);
}
Also curious why I'm seeing so much raw sqlite3 work these days - any reason you're not using Core Data? Just a suggestion - it may not fit your needs (i.e., schema already exists and you're downloading it directly, etc).

Problem With Sqlite Data Retrieving

I have an SQLite database, and when I am trying to get the data from the database, I get the last inserted element repeatedly. How can I get all the elements with no repetition.
The code I've written:
- (NSMutableArray *) gettingData {
sqlDict = [[NSMutableDictionary alloc] init];
membersInfoArray =[[NSMutableArray alloc]init ];
[self checkAndCreateDatabase];
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "select * from ProductList";
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSString *prdbcode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
[sqlDict setObject:prdbcode forKey:#"Barcode"];
[prdbcode release];
NSString *prdname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
[sqlDict setObject:prdname forKey:#"ProductName"];
[prdname release];
NSString *prdDesc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
[sqlDict setObject:prdDesc forKey:#"ProductDescription"];
[prdDesc release];
NSString *prdstatus = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)];
[sqlDict setObject:prdstatus forKey:#"ProductStatus"];
[prdstatus release];
[membersInfoArray addObject:sqlDict];
[sqlDict release];
}
}
sqlite3_finalize(selectstmt);
}
sqlite3_close(database);
return membersInfoArray;
}
I am retrieving the data as follows:
NSMutableArray *sqlArray = [sqlViewController gettingData];
Thank you.
Just Declare your array globally instead of declare locally in your method. Your problem will resolved.