Fast access to Core Data database information? - iphone

i have iOS application with core data, in one of my function i load the information to display one view of my application in this way:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"MyDate" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
if ([[[info valueForKey:#"status"] description] isEqualToString:#"Done"]) {
NSArray *allTask = [[info valueForKey:#"taskes"] allObjects];
for (NSManagedObject *task in allTask) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
if (IsDateBetweenInclusive([task valueForKey:#"firstDate"], fromDate, toDate)) {
[taskArray addObject:task];
}
}
}
}
so i iterate all database to find the information and then display it, when the information in my database are few the method above is fast, but when the information in my database is more, on my 3GS take some seconds to display that view, instead in the simulator is fast, so my question is, there is a fast way, to take information from core date? i don't know there is a fast call with the attribute and the value i want retrieve from core data?
thanks

Use NSPredicate, see https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html
The following piece of code will only fetch the values where the status field is set to 'Done'
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"MyDate" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"status == 'Done'"]];
NSError *error;
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

Create database:
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"newapp.sqlite"]];
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 LIST (id VARCHAR, title VARCHAR , description VARCHAR ,date VARCHAR)";
if ((sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) )
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Warning" message:#"Failed to create table" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
sqlite3_close(contactDB);
} else {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Warning" message:#"Failed to open/create database" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
Insert values
NSString *id_str=#"21";
NSString *title=#"notisa";
NSString *description=#"new app";
NSString *date=#"21/4/30";
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK){
// error handling...
}
// Construct the query and empty prepared statement.
const char *sql = "INSERT INTO `LIST` (`id`,`title`,`description`,`date`) VALUES (?, ?, ?, ?)";
sqlite3_stmt *statement;
// UIImage *image = [UIImage imageWithData:imgdata];
//NSData *imageData=UIImagePNGRepresentation(image);
// Prepare the statement.
if (sqlite3_prepare_v2(contactDB, sql, -1, &statement, NULL) == SQLITE_OK) {
// Bind the parameters (note that these use a 1-based index, not 0).
sqlite3_bind_text(statement,1, [id_str UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement,2, [title UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement,3, [description UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement,4, [date UTF8String], -1, SQLITE_TRANSIENT);
}
// Execute the statement.
if (sqlite3_step(statement) != SQLITE_DONE) {
// error handling...
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Warning" message:#"Failed to Save" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Database" message:#"Stored Successfully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
// Clean up and delete the resources used by the prepared statement.
sqlite3_finalize(statement);
sqlite3_close(contactDB);
Select Database:
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT id,title,description,date FROM LIST"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"ROW-->%d",SQLITE_ROW);
const char* policyNo = (const char *)sqlite3_column_text(statement, 1);
NSString *PolicyNumber = policyNo == NULL ? nil : [[NSString alloc]initWithUTF8String:policyNo];
NSLog(#"PolicyNumber:%#",PolicyNumber);
const char* start = (const char *)sqlite3_column_text(statement, 2);
NSString *startDate = start == NULL ? nil : [[NSString alloc]initWithUTF8String:start];
const char* end = (const char *)sqlite3_column_text(statement, 3);
NSString *endDate = end == NULL ? nil : [[NSString alloc]initWithUTF8String:end];
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
Delete :
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"DELETE id,title,description,date FROM LIST"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"ROW-->%d",SQLITE_ROW);
const char* policyNo = (const char *)sqlite3_column_text(statement, 1);
NSString *PolicyNumber = policyNo == NULL ? nil : [[NSString alloc]initWithUTF8String:policyNo];
NSLog(#"PolicyNumber:%#",PolicyNumber);
const char* start = (const char *)sqlite3_column_text(statement, 2);
NSString *startDate = start == NULL ? nil : [[NSString alloc]initWithUTF8String:start];
const char* end = (const char *)sqlite3_column_text(statement, 3);
NSString *endDate = end == NULL ? nil : [[NSString alloc]initWithUTF8String:end];
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}

Related

How to list the resultset based on order using query

//===================================================================================
- ( NSMutableDictionary * ) getDataToDisplayTierTwo:(NSString*)dbPath:(NSString*)iD{
//===================================================================================
NSMutableDictionary *aTierTwoTemplateData = [[NSMutableDictionary alloc]init];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *selectSQL = [NSString stringWithFormat: #"select * from sub_categories_reference scr inner join storyboard_sub_categories ssc on ssc.id = scr.sub_category_id inner join subcategory_order as sco on sco.sub_category_id = scr.sub_category_id where scr.main_category_id = %# and sco.main_category_id = %# order by sco.position asc",iD,iD];
NSLog(#"%#", selectSQL);
const char *sql_query_stmt = [selectSQL UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql_query_stmt, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSString *aValue = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 6)];
NSString *aId = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 5)];
[aTierTwoTemplateData setObject:aId forKey:aValue];
[aValue release];
[aId release];
NSLog(#"%# %# ^^^^^^^^^^^^^^^^^^^^picker value id ", aValue, aId);
}
}
}
sqlite3_close(database);
return aTierTwoTemplateData;
}
I am able to get the resultset when i assign this to array , but it loses the order in which , i have stored in the dictionery.
Actually , i have stored the result set based on the position field .
When i assign the resultset into array , the order gets changed.
Please let me know how can i handle this situation.
This is not a duplicate, as i have a coulmn in the db as "position"
If you want to store data as key-value pair and maintain the order, then you can use combination of NSArray and NSDictionary.The same code will be:
//===================================================================================
- ( NSArray * ) getDataToDisplayTierTwo:(NSString*)dbPath:(NSString*)iD{
//===================================================================================
NSMutableArray *aTierTwoTemplateData = [[NSMutableArray alloc]init];
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *selectSQL = [NSString stringWithFormat: #"select * from sub_categories_reference scr inner join storyboard_sub_categories ssc on ssc.id = scr.sub_category_id inner join subcategory_order as sco on sco.sub_category_id = scr.sub_category_id where scr.main_category_id = %# and sco.main_category_id = %# order by sco.position asc",iD,iD];
NSLog(#"%#", selectSQL);
const char *sql_query_stmt = [selectSQL UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql_query_stmt, -1, &selectstmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(selectstmt) == SQLITE_ROW)
{
NSString *aValue = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 6)];
NSString *aId = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selectstmt, 5)];
[aTierTwoTemplateData addObject:[NSDictionary dictionaryWithObject:aId forKey:aValue]];
[aValue release];
[aId release];
NSLog(#"%# %# ^^^^^^^^^^^^^^^^^^^^picker value id ", aValue, aId);
}
}
}
sqlite3_close(database);
return [aTierTwoTemplateData autorelease];
}
In this way you'll be having an array of dictionaries, where your values will be stored in the dictionary and the order of the data also will be preserved.

not able to insert record in table in objective c

I made iPad application in which,
I want to insert record into database table, but I am unable to do the same.
here is my code snippet,
-(void) insertRecordIntoTableNamed: (NSString *) symbol{
NSString *sql = [NSString stringWithFormat:#"INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('%#',datetime())",symbol];
NSLog(#"sql=%#",sql);
char *err;
if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK)
{
sqlite3_close(db);
NSAssert(0, #"Error updating table.");
}
}
my NSLog shows:
sql=INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('PATNI',datetime())
this statement is correct, but i am unable to see VALUES PATNI and datetime() in my database table
here is rest of the code,
NSString *filePahs = Nil;
-(NSString *) filePath {
filePahs=[[NSBundle mainBundle] pathForResource:#"companymaster" ofType:#"sql"];
NSLog(#"path=%#",filePahs);
return filePahs;
}
result of above method is:
path=/Users/krunal/Library/Application Support/iPhone Simulator/5.0/Applications/9FF61238-2D1D-4CB7-8E24-9AC7CE9415BC/iStock kotak.app/companymaster.sql
-(void) openDB {
//---create database---
if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK )
{
sqlite3_close(db);
NSAssert(0, #"Database failed to open.");
}
}
-(void) getAllRowsFromTableNamed: (NSString *) tableName {
//---retrieve rows---
NSString *qsql = #"SELECT * FROM recentquotes";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2( db, [qsql UTF8String], -1, &statement, nil) ==
SQLITE_OK) {
NSLog(#"b4 while");
while (sqlite3_step(statement) == SQLITE_ROW)
{
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
[recentqotarray addObject:field1Str];
[field1Str release];
}
//---deletes the compiled statement from memory---
sqlite3_finalize(statement);
NSLog(#"recentqotarray=%#",recentqotarray);
}
}
edit
i wrote this, and when i checked my log i got like this, "in find data" , i didn't got my sql=...
- (void) finddata
{
NSString *databasePath;
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
NSLog(#"in finddata");
if (sqlite3_open(dbpath, &db) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM recentquotes"];
NSLog(#"sql=%#",querySQL);
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(#"Inside recent quote table");
char *field1 = (char *) sqlite3_column_text(statement, 0);
NSLog(#"Column name=%s",field1);
NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
[recentqotarray addObject:field1Str];
NSLog(#"array=%#",recentqotarray);
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
}
Thanks In Advance
In your:
NSString *sql = [NSString stringWithFormat:#"INSERT INTO recentquotes ('symbol', 'dt_tm') VALUES ('%#',datetime())",symbol];
Instead of '%#' try using \"%#\" , and check if it inserts into your db.
EDIT:
I've been working on DB a lot lately, and i've been able to successfully insert data in my sqlite, i'll write down what i use check if it helps:
NSArray*dirPath;
NSString*docDir;
dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docDir=[dirPath objectAtIndex:0];
databasePath=[docDir stringByAppendingPathComponent:#"example.sqlite"];
BOOL success;
NSFileManager*fm=[NSFileManager defaultManager];
success=[fm fileExistsAtPath:databasePath];
if(success)
{
NSLog(#"Already present");
}
NSString*bundlePath=[[NSBundle mainBundle] pathForResource:#"example" ofType:#"sqlite"];
NSError*error;
success=[fm copyItemAtPath:bundlePath toPath:databasePath error:&error];
if(success)
{
NSLog(#"Created successfully");
}
const char*dbPath=[databasePath UTF8String];
if(sqlite3_open(dbPath, &myDB)==SQLITE_OK)
{
NSString*insertSQL=[NSString stringWithFormat:#"insert into extable (name) values (\"%#\")",[nametextField.text]];
const char*insertStmt=[insertSQL UTF8String];
char *errmsg=nil;
if(sqlite3_exec(myDB, insertStmt, NULL, NULL, &errmsg)==SQLITE_OK)
{
NSLog(#"ADDED!");
}
sqlite3_close(myDB);
}

How to retrieve a particular column from a database in iphone

in my project im using a database.There are almost 365 questions in that.so i want to get a particulat question for a particular day.i used the code below to fetch a qusestion from database.
-(void)print{
sqlite3_stmt *statement;
// SELECT * from light where rowid = %i",1
qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '365'"];
if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"%dsssssssssssssss",sqlite3_step(statement));
NSLog(#"%ddddddddddddddddddddd", (SQLITE_ROW));
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSLog(#"%# gg",Q_NO);
when i use the above code it is printing the correct question from database.Also when i give the statement like qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '1'"]; it is not fetching the question.
But when i use the below code it is not fetching from the database.
-(void)print{
sqlite3_stmt *statement;
// SELECT * from light where rowid = %i",1
qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '1'"];
if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"%dsssssssssssssss",sqlite3_step(statement));
NSLog(#"%ddddddddddddddddddddd", (SQLITE_ROW));
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSLog(#"%# gg",Q_NO);
while (sqlite3_step(statement) == (SQLITE_ROW))
{
NSLog(#" iolo");
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
//NSString *Q_NO = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%i",sqlite3_column_int(statement, 0)]];
NSLog(#"%# gg",Q_NO);
}
sqlite3_reset(statement);
}
sqlite3_finalize(statement);
}
Can anyone tell me where im going wrong.Thanks in advance.
-(void)print{
sqlite3_stmt *statement;
qsql=[NSString stringWithFormat:#"Select * from ishh where col_1 = '1'"];
if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == (SQLITE_ROW))
{
char *field0 = (char *)sqlite3_column_text(statement, 0);
char *field1 = (char *)sqlite3_column_text(statement, 1);
NSString *Q_NO = nil;
if(field0!=NULL){
Q_NO = [[NSString alloc] initWithUTF8String:field0];
}
NSString *Q_NO1 = nil;
if(field1!=NULL){
Q_NO1 = [[NSString alloc] initWithUTF8String:field1];
}
NSLog(#"%# %#",Q_NO, Q_NO1);
[Q_NO release];
[Q_NO1 release];
}
}
sqlite3_finalize(statement);
}

Query is not retrieving the data from table

im trying to integrate a database into my project.This is for first time im implementing a database project.I integrated the database into my project.Database has 3 columns named rowid,col1,col2.Below code i used for acessing the datafrom database.But it is not enetering in "if loop"Can anyone help me where im doing wrong in this case.Thanks in advance.![enter image description here][1]
/* -(void)print
{
sqlite3_stmt *statement;
qsql=[NSString stringWithFormat:#"SELECT * from light where rowid = '%d'",1];
if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"hhhhhhhhh");
while (sqlite3_step(statement) == (SQLITE_ROW)){
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
// tv.text=qsql;
}
}}*/
-(void)print
{
sqlite3_stmt *statement;
//qsql=[NSString stringWithFormat:#"SELECT * from light where rowid = %d",1];
qsql=[NSString stringWithFormat:#"SELECT * from light where rowid = %i",1];
//const char *sqlStatement = [qsql cStringUsingEncoding:NSUTF8StringEncoding];
const char *qsql_stament = [qsql cStringUsingEncoding:NSUTF8StringEncoding];
if(sqlite3_prepare_v2(database, qsql_stament, -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"hhhhhhhhh");
while (sqlite3_step(statement) == (SQLITE_ROW)){
// NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
NSString *Q_NO = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%i",sqlite3_column_int(statement, 0)]];
// tv.text=qsql;
}
}
}
-(void) checkAndCreateDatabase{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if(success) return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];
}
-(void) openDB {
databaseName = #"Lighthr.sqlite";
NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentsPaths objectAtIndex:0];
databasePath = [documentDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
if(sqlite3_open([databasePath UTF8String],&database) == SQLITE_OK){
NSLog(#"coming here???");
}
}
[1]: http://i.stack.imgur.com/lm1ZV.png
because rowid is always integer and you are trying to access using string.
I thing you have to try this.
Edit
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
qsql=[NSString stringWithFormat:#"SELECT * from light where rowid = %i",1];
const char *sqlStatement = [qsql cStringUsingEncoding:NSUTF8StringEncoding];
if(sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"hhhhhhhhh");
while (sqlite3_step(statement) == (SQLITE_ROW)){
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
// tv.text=qsql;
}
}
}
Are you trying to test without your "where" clause ?
And what is the error code return by sqlite3_prepare_v2 ?
int sql_answer = sqlite3_prepare_v2(database, qsql_stament, -1, &statement, NULL);
NSLog(#" SQL answer : %d",sql_answer );
if(sql_answer == SQLITE_OK) {
...
i think you should do in this way .
-(void)print
{
sqlite3_stmt *statement;
qsql=[NSString stringWithFormat:#"SELECT * from light where rowid = %d",1];
const char *qsql_stament = [qsql cStringUsingEncoding:NSUTF8StringEncoding];
if(sqlite3_prepare_v2(database, qsql_stament, -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"hhhhhhhhh");
while (sqlite3_step(statement) == (SQLITE_ROW)){
NSString *Q_NO =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]
}
NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
above stameny replace with below statement
NSString *Q_NO = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%i",sqlite3_column_int(statement, 0)]];
and
const char *qsql_stament = [qsql cStringUsingEncoding:NSUTF8StringEncoding];
now replace [qsql UTF8String] with qsql_stament. It will work fine.

Sqlite database file is getting encrypted or is not a database

I have no idea what was the problem is in my program. When run this select code for fetching data from SQlite in my program, the first time it crashes with this error message:
kill error while killing target (killing anyway):
warning: error on line 2179 of "/SourceCache/gdb/gdb-1510/src/gdb/macosx/macosx-nat-inferior.c" in function "macosx_kill_inferior_safe": (os/kern) failure (0x5x)
quit
Here's my insert code:
-(id)init {
self = [super init];
sqlite3 *database;
NSMutableArray *locations;
NSString *result = nil;
NSString *dbPath = [self getWritableDBPath];
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
NSString *sqlStr = [NSString stringWithFormat:#"select Longitude,Latitude from myLocation"];
const char *sqlStatement = [sqlStr UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
locations = [NSMutableArray array];
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
double longitude = sqlite3_column_double(compiledStatement, 0);
double latitude = sqlite3_column_double(compiledStatement, 1);
NSLog(#"%f , %f",longitude,latitude);
NSString *coords = [[[NSString alloc] initWithFormat:#"%f,%f\n",longitude,latitude] autorelease];
[locations addObject:coords];
NSLog(#"this location :-%#",locations);
//[coords release];
}
result = [locations componentsJoinedByString:#","]; // same as `fake_location`
NSLog(#"this for resulte data :- %#",result);
// Get file path here
NSError *error;
if ( [result writeToFile:dbPath atomically:YES encoding:NSUTF8StringEncoding error:&error] ) {
NSLog(#"%#", [error localizedDescription]);
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
pointsArray = [[result componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] retain];
pointsArrayIndex = 0;
oldLocationsIndex = 0;
[result release];
oldLocations = [[NSMutableArray alloc] init];
return self;
}
The second time I run my application, it shows me that on the console:
Save Error: file is encrypted or is not a database
What do these errors mean, and how do I solve that?
You need to fire insert query using following:
-(void)insertLocation:(double)latitude withLongitude:(double)longitude
{
sqlite3_stmt *insertStatement = nil;
const char *sql = "insert into UserJourneyLocation(Latitude, Longitude) Values(?,?)";
int returnValue = sqlite3_prepare_v2(database, sql, -1, &insertStatement, NULL);
if(returnValue == SQLITE_OK)
{
sqlite3_bind_double(insertStatement,1,latitude);
sqlite3_bind_double(insertStatement,2,longitude);
if(sqlite3_step(insertStatement)==SQLITE_DONE)
{
//Data;
}
}
sqlite3_finalize(insertStatement);
}
Yes I have.
Go to iphone application document folder
/users/(yourname)/library/application support/iphone simulator/user/application
And remove all Targets.After that Restart your application.