Potential Leak of an object - iphone

I am facing Potential leak of an object allocated. So how can I release my custom class object in loop . I am enclosing my code below herewith.
- (ProfileClass *) getUserProfile
{
NSString *query = [NSString stringWithFormat:#"SELECT * FROM Profile"];
NSLog(#"query %#",query);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"MOFAdb.sqlite"];
ProfileClass *profile = nil;
// Open the database. The database was prepared outside the application.
if(sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
sqlite3_stmt *Statement1;
//int i=0;
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &Statement1, NULL) == SQLITE_OK) {
//int returnValue = sqlite3_prepare_v2(database, sql, -1, &Statement1, NULL);
if (sqlite3_step(Statement1) == SQLITE_ROW) {
// The second parameter indicates the column index into the result set.
NSString *userName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(Statement1, 0)];
NSString *userEmail = [NSString stringWithUTF8String:(char *)sqlite3_column_text(Statement1, 1)];
NSString *phoneNum = [NSString stringWithUTF8String:(char *)sqlite3_column_text(Statement1, 2)];
//int phone = sqlite3_column_int(Statement1, 2);
//NSLog(#"%d",phone);
//RecipeClass *rc = [[RecipeClass alloc] getRecipe:recipeName withRecipeIng:recipeIng withRecipeInst:recipeInstru withRecipeTips:recipeTips withRecipeDesc:recipeDesc];
if (profile)
[profile release];
profile = [[ProfileClass alloc] getProfileInfo:userName withEmail:userEmail withPhone:phoneNum];
//NSLog(#"%#",fact);
//NSLog(#"%d",i);
//i++;
}
}
//Release the select statement memory.
sqlite3_finalize(Statement1);
//}
}
else {
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSAssert1(0, #"Failed to open database with message '%s'.", sqlite3_errmsg(database));
// Additional error handling, as appropriate...
}
return profile;
}
If I autorelease my profile = [[[ProfileClass alloc] getProfileInfo:userName withEmail:userEmail withPhone:phoneNum] autorelease]; so my application crashes later. So I m release on if check but build and Analyze shows it as a warning.

You can also autorelease like that:
return [profile autorelease];
and retain the object of ProfileClass where you used it,
Ex- ProfileClass *objProfile=[[database getUserProfile] retain];
and release objProfile when you used it.

Your method: - (ProfileClass *) getUserProfile is not an instance method or a copy you should return an object that is autoreleased. But you should do it on the last line, since you have a if/else structure and if you only autorelease it on line profile = [[[ProfileClass alloc] getProfileInfo:userName withEmail:userEmail withPhone:phoneNum] autorelease]; it will not get autoreleased if it fails the if statement and goes to else. So just do this:
return [profile autorelease];

Why don't you do:
return [profile autorelease];
And there is no need for the
if (profile)
check. Just release unconditionally. If profile is nil, it won't have any negative effect.
FWIW: I don't quite understand what your getProfile:etc... method does. I assume it is an initializer and nothing more (like the many initXYZ: methods in Cocoa). If so, you should probably call it initWithUserName:email:phone: to go with the convention. Could you post the method?

using an array you can solve this issue before calling this method
NSMutableArray *ProfileArray=[[NSMutableArray alloc] initWithArray:[ClassObj getUserProfile]];
ProfileClass *profileObj=[[ProfileArray objectAtIndex:0] retain];
[ProfileArray release];
// now you can use profile object anywhere... I hope memory issue is also solved
- (NSMutableArray *) getUserProfile
{
NSMutableArray *array=[[NSMutableArray alloc] init];
NSString *query = [NSString stringWithFormat:#"SELECT * FROM Profile"];
NSLog(#"query %#",query);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"MOFAdb.sqlite"];
ProfileClass *profile = nil;
// Open the database. The database was prepared outside the application.
if(sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
sqlite3_stmt *Statement1;
//int i=0;
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &Statement1, NULL) == SQLITE_OK) {
//int returnValue = sqlite3_prepare_v2(database, sql, -1, &Statement1, NULL);
if (sqlite3_step(Statement1) == SQLITE_ROW) {
// The second parameter indicates the column index into the result set.
NSString *userName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(Statement1, 0)];
NSString *userEmail = [NSString stringWithUTF8String:(char *)sqlite3_column_text(Statement1, 1)];
NSString *phoneNum = [NSString stringWithUTF8String:(char *)sqlite3_column_text(Statement1, 2)];
//int phone = sqlite3_column_int(Statement1, 2);
//NSLog(#"%d",phone);
//RecipeClass *rc = [[RecipeClass alloc] getRecipe:recipeName withRecipeIng:recipeIng withRecipeInst:recipeInstru withRecipeTips:recipeTips withRecipeDesc:recipeDesc];
if (profile)
[profile release];
profile = [[ProfileClass alloc] getProfileInfo:userName withEmail:userEmail withPhone:phoneNum];
[array addObject:profile];
[profile release];
}
}
//Release the select statement memory.
sqlite3_finalize(Statement1);
//}
}
else {
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSAssert1(0, #"Failed to open database with message '%s'.", sqlite3_errmsg(database));
// Additional error handling, as appropriate...
}
return [array autorelease];
}
I hope it will be helpful to you
cheers

Related

How to store image in sqlite database in iphone? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"image.sqlite"];
if (sqlite3_open_v2([path UTF8String], &database, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK)
{
if(selectStmt == nil)
{
const char *sql = "insert into imagetb(imagename,image) Values(?,?)";
if(sqlite3_prepare_v2(database, sql, -1, &selectStmt, NULL) != SQLITE_OK)
// NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
NSLog(#"%s",sqlite3_errmsg(database));
}
sqlite3_bind_text(selectStmt, 1, [#"test.png" UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(selectStmt, 2, [data1 bytes], [data1 length], SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(selectStmt))
NSLog(#"get: %s",sqlite3_errmsg(database));
else
NSLog(#"scan data added");
}
//showimage
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
const char *sql = "select * from imagetb";// LIMIT 0,100 ";// where status = 1 ";
sqlite3_stmt *selectstatment;
if (sqlite3_prepare_v2(database, sql, -1, &selectstatment, NULL) == SQLITE_OK)
{
while (sqlite3_step(selectstatment) == SQLITE_ROW)
{
NSString *getorgstrid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstatment, 0)];
NSLog(#"id->%#",getorgstrid);
[getid addObject:getorgstrid];
NSString *getorgstrname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstatment, 1)];
NSLog(#"name->%#",getorgstrname);
[getname addObject:getorgstrname];
NSData *getorgstrimage = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstatment,2)length:sqlite3_column_bytes(selectstatment, 2)];
[getimage addObject:getorgstrimage];
}
}
sqlite3_finalize(selectstatment);
}
//[tblorgland reloadData];
UIImage *image1 = [UIImage imageWithData:[getimage lastObject]];
NSLog(#"image%#",image1);
[getImageview setImage:image1];
[pool release];
==============================================================================
- (NSString *) getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"image.sqlite"];
}
- (void)viewDidLoad
{
[super viewDidLoad];
getid=[[NSMutableArray alloc]init];
getname=[[NSMutableArray alloc]init];
getimage=[[NSMutableArray alloc]init];
[self downloadimage];
[self makeDBCopyAsNeeded];
}
-(void)downloadimage
{
NSLog(#"Downloading...");
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://0.tqn.com/d/graphicssoft/1/7/g/A/5/psptubezdotcom_003.png"]]];
NSLog(#"%f,%f",image.size.width,image.size.height);
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(#"%#",docDir);
NSLog(#"saving png");
pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir];
data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
img=[[UIImage alloc]initWithData:data1];
[data1 writeToFile:pngFilePath atomically:YES];
NSLog(#"saving jpeg");
NSString *jpegFilePath = [NSString stringWithFormat:#"%#/test.jpeg",docDir];
NSLog(#"jpegFilePath:%#",jpegFilePath);
data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[data2 writeToFile:jpegFilePath atomically:YES];
NSLog(#"saving image done");
[image release];
}
- (void) makeDBCopyAsNeeded
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"image.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
NSString *dbPath = [self getDBPath];
NSLog(#"%#",dbPath);
if (success)
{
NSLog(#"Database Success Created");
return;
}
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"image.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success)
{
NSLog(#"Database:->%s",sqlite3_errmsg(database));
}
}
It is not recommended to store the image data in the sqlite. But if you want to store the image data then use this link
Save image data to sqlite database in iphone
Hope this will helps you..
You better use caches to store your images, and use database to store their names or some unique id's
Just write following code in -(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo: if you are getting image from gallery or Camera otherwise skip code under if (imageData != nil) and just use below code to save image in sqlite
NSData * imageData = UIImageJPEGRepresentation(image, 0.8);
NSLog(#"Image data length== %d",imageData.length);
if (imageData != nil)
{
UIImage *resizedImg = [self scaleImage:[UIImage imageWithData:imageData] toSize:CGSizeMake(150.0f,150.0f)];
NSData * imageData = UIImageJPEGRepresentation(resizedImg, 0.2);
NSLog(#"*** Image data length after compression== %d",imageData.length);
NSString *nameofimg=[NSString stringWithFormat:#"%#",resizedImg];
NSString *substring=[nameofimg substringFromIndex:12];
NSString *new=[substring substringToIndex:7];// Get image name
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdirectory=[path objectAtIndex:0];
NSString *newFilePath = [NSString stringWithFormat:[documentdirectory stringByAppendingPathComponent: #"/%#.png"],new];
[imageData writeToFile:newFilePath atomically:YES];
imgpath=[[NSString alloc]initWithString:newFilePath];
NSLog(#"doc img in img method === %#",imgpath);
}
databasepath=[app getDBPath]; // i have this method in delegate
if (sqlite3_open([databasepath UTF8String], &dbAssessor) == SQLITE_OK)
{
NSString *selectSql = [NSString stringWithFormat:#"insert into imagetb(imagename,image) VALUES(\"%#\",\"%#\") ;",yourImgName,imgpath];
NSLog(#"Query : %#",selectSql);
const char *sqlStatement = [selectSql UTF8String];
sqlite3_stmt *query_stmt;
sqlite3_prepare(dbAssessor, sqlStatement, -1, &query_stmt, NULL);
if(sqlite3_step(query_stmt)== SQLITE_DONE)
{
NSLog(#"home image updated. :)");
app.houseImage=imgpath;
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Sorry" message:#"Failed To Save Home Image." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
sqlite3_finalize(query_stmt);
}
sqlite3_close(dbAssessor);

Searching SQLite3 DB in iPhone from input given in UITextfield

I am fairly new to iOS development. I am trying to build application which searches given search term in sqllite3 DB. I am having trouble with binding parameter to that sql statement.Following is my code to read data from database.
-(void) readPlayersFromDatabase
{
NSString * strTemp=[[NSString alloc]init];
strTemp=#"ben";
sqlite3 *database;
players = [[NSMutableArray alloc] init];
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
char *sqlStatement = "SELECT * FROM Player WHERE LENGTH (lastname)>0 AND LENGTH (firstname)>0 AND ( lastname LIKE '%?%' OR firstname LIKE'%?%' OR Height LIKE '%?%' OR Weight LIKE '%?%') ORDER BY lastname,firstname";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
sqlite3_bind_text(compiledStatement, 1, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
sqlite3_bind_text(compiledStatement, 2, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
sqlite3_bind_text(compiledStatement, 3, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
sqlite3_bind_text(compiledStatement, 4, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
NSString *playerId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *playerName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
Player *temp = [[Player alloc] initWithID:playerId name:playerName];
[players addObject:temp];
[temp release];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
All I am getting at the end is name of player which has ? in their name. Can anyone help me out here. Can you also tell me how can I connect UITextfield input to the strTemp in above code ?
Thanks.
What do you want to do exactly? You can send as a parameter to your readPlayersFromDatabase method to your UITextfield input.
Here is my method to select command: I had a class which is called DBOperations. I hope that helps
+ (int) getUserID{
//check DB
if (![DBOperations checkDB])
{
NSString *msgAlert = #"can not access db file.";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Connection error" message:msgAlert
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
return 0;
}
[DBOperations open];
int _userID = 1;
const char* sql = " select id from Oyuncu ORDER BY id desc";
if (sqlite3_prepare_v2(database, sql, -1, &hydrate_statement, NULL) != SQLITE_OK) {
NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
if (sqlite3_step(hydrate_statement)==SQLITE_ROW)
{
_userID= sqlite3_column_int(hydrate_statement,0);
NSLog(#"%d",_userID);
}
// Execute the query.
sqlite3_finalize(hydrate_statement);
return _userID;
[DBOperations close];
}
+(BOOL) checkDB {
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"dbOyun.db"];
BOOL success = [fileManager fileExistsAtPath:writableDBPath];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return true;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"dbOyun.db"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
return success;
}
+ (void) open{
//check db validity
NSString *dbPath;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
dbPath = [documentsDirectory stringByAppendingPathComponent:#"dbOyun.db"];
if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
sqlite3_close(database);
NSAssert1(0, #"Failed to open database with message '%s'.", sqlite3_errmsg(database));
}
}

Problem while scrolling Table View

I have the following problem while i scroll the table view:
NSCFString objectAtIndex:]: unrecognized selector sent to instance
I create NSDictionary tableContents and when i scroll it becomes deallocated.
This is my code:
- (void)viewDidLoad {
lessonsInGroup1 = [NSMutableArray array];
lessonsInGroup2 = [NSMutableArray array];
lessonsInGroup1 = [self grabRowsInGroup:#"1"];
lessonsInGroup2 = [self grabRowsInGroup:#"2"];
NSDictionary *temp =[[NSDictionary alloc]initWithObjectsAndKeys:lessonsInGroup1,#"General Information",lessonsInGroup2,#"LaTeX Examples", nil];
//[[tableContents alloc] init];
self.tableContents =temp;
[temp release];
NSLog(#"table %#",self.tableContents);
NSLog(#"table with Keys %#",[self.tableContents allKeys]);
self.sortedKeys =[[self.tableContents allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sorted %#",self.sortedKeys);
[lessonsInGroup1 release];
[lessonsInGroup2 release];
//[table reloadData];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
[super viewDidLoad];
}
- (NSMutableArray *) grabRowsInGroup:(NSString*)GroupID{
NSMutableArray *groupOfLessons;
groupOfLessons = [[NSMutableArray alloc] init];
char *sqlStatement;
int returnCode;
sqlite3_stmt *statement;
NSString *databaseName;
NSString *databasePath;
// Setup some globals
databaseName = #"TexDatabase.sql";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
// Setup the database object
sqlite3 *database;
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK) {
fprintf(stderr, "Error in opening the database. Error: %s",
sqlite3_errmsg(database));
sqlite3_close(database);
return;
}
sqlStatement = sqlite3_mprintf(
"SELECT * FROM Lessons WHERE LessonGroup = '%s';", [GroupID UTF8String]);
returnCode =
sqlite3_prepare_v2(database,
sqlStatement, strlen(sqlStatement),
&statement, NULL);
if(returnCode != SQLITE_OK) {
fprintf(stderr, "Error in preparation of query. Error: %s",
sqlite3_errmsg(database));
sqlite3_close(database);
return;
}
returnCode = sqlite3_step(statement);
while(returnCode == SQLITE_ROW) {
NSString *aLessonID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
NSString *aLessonGroup = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSString *aLessonTopic = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
NSString *aLessonText = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
NSString *aLessonCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 4)];
NSString *aLessonPicture = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 5)];
/*NSLog(aLessonID);
NSLog(aLessonGroup);
NSLog(aLessonTopic);
NSLog(aLessonText);
NSLog(aLessonCode);
NSLog(aLessonPicture);*/
// Create a new busCit object with the data from the database
Lesson *lesson = [[Lesson alloc] initWithLessonID:aLessonID LessonGroup:aLessonGroup LessonTopic:aLessonTopic LessonText:aLessonText LessonCode:aLessonCode LessonPicture:aLessonPicture];
[groupOfLessons addObject:lesson];
returnCode = sqlite3_step(statement);
}
sqlite3_finalize(statement);
sqlite3_free(sqlStatement);
return [groupOfLessons autorelease];
}
What does your #property for tableofContents look like?
Also, you are going to run into issues with
[lessonsInGroup1 release];
[lessonsInGroup2 release];
because you are autoreleasing those in the grabRowsInGroup:
So, you don't need to call release them.
Looks like you are calling objectAtIndex on NSString. It should rather be some array

the SQLiteBooks sample code is missing

I find this link everywhere for SQLite sample code (http://developer.apple.com/library/ios/#samplecode/SQLiteBooks/index.html) but either it has been removed or changed to another location.. I couldn't find it in google searches.. Does anyone know any other link to the code or any other good sample code for SQLite?
May be this is useful to you.
http://www.switchonthecode.com/tutorials/using-sqlite-on-the-iphone
http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/
http://www.icodeblog.com/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/
You can use this class and send query in this class and get all functionality of sqlite using this class
.h
#import <Foundation/Foundation.h>
#import "sqlite3.h"
#interface DBLib : NSObject {
sqlite3 *database;
NSString *path;
}
- (NSString *)getDatabasePath:(NSString*)DBName;
- (void)createEditableCopyOfDatabaseIfNeeded:(NSString*)DBName;
- (void)initializeDatabase:(NSString*)DBName;
-(NSMutableArray*)GetListBySQL:(NSString*)SQL;
-(BOOL)UpdateData:(NSMutableDictionary*)objDic :(NSString*)PrimaryKey :(NSString*)TABLE_NAME;
-(BOOL)deleteQuery:(NSString *)query;
#end
.m
#import "DBLib.h"
#implementation DBLib
#pragma mark Database methods
- (NSString *)getDatabasePath:(NSString*)DBName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;
NSString *documentsDirectory = [paths objectAtIndex:0] ;
return [documentsDirectory stringByAppendingPathComponent:DBName];
}
// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded:(NSString*)DBName {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DBName];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DBName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSString *errString = [NSString stringWithFormat:#"%#", [#"Fail" stringByReplacingOccurrencesOfString:#"#" withString:[error localizedDescription] ]];
NSAssert1(0, #"%#", errString);
}
}
// Open the database connection and retrieve minimal information for all objects.
- (void)initializeDatabase:(NSString*)DBName {
// The database is stored in the application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
path = [documentsDirectory stringByAppendingPathComponent:DBName];
NSStringEncoding enc = [NSString defaultCStringEncoding];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
//TRUE
NSLog(#"Successfully opened-sqlite3");
}
else
{
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSLog(#"closed");
NSString *errString = [NSString stringWithFormat:#"%#", [#"Fail" stringByReplacingOccurrencesOfString:#"#" withString:[NSString stringWithCString:sqlite3_errmsg(database) encoding:enc] ]];
NSAssert1(0, #"%#", errString);
// Additional error handling, as appropriate...
}
}
-(NSMutableArray*)GetListBySQL:(NSString*)SQL
{
[self initializeDatabase:#"DBNAME"];
NSMutableArray* Array;
Array=[[NSMutableArray alloc]init];
NSStringEncoding enc = [NSString defaultCStringEncoding];
sqlite3_stmt *select_statement=nil;
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &select_statement, NULL) != SQLITE_OK) {
NSString *errString = [NSString stringWithFormat:#"%#", [#"Fail" stringByReplacingOccurrencesOfString:#"#" withString:[NSString stringWithCString:sqlite3_errmsg(database) encoding:enc] ]];
NSAssert1(0, #"%#", errString);
}
int columncount=sqlite3_column_count(select_statement);
NSMutableDictionary* dic;
while (sqlite3_step(select_statement) == SQLITE_ROW)
{
dic=[[NSMutableDictionary alloc]init];
for(int j=0;j<columncount;j++)
{
if(sqlite3_column_text(select_statement, j)!=nil)
[dic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(select_statement, j)] forKey:[NSString stringWithUTF8String:(char *)sqlite3_column_name(select_statement,j)]];
else
[dic setObject:#"" forKey:[NSString stringWithUTF8String:(char *)sqlite3_column_name(select_statement,j)]];
}
[Array addObject:dic];
[dic release];
}
sqlite3_finalize(select_statement);
NSMutableArray *arr = [[NSMutableArray alloc] initWithArray: Array];
[Array release];
return arr;
}
//Method for Datbase
-(BOOL)UpdateData:(NSMutableDictionary*)objDic :(NSString*)PrimaryKey :(NSString*)TABLE_NAME
{
NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
[self initializeDatabase:DBNAME];
NSString* SQLColumns=#"";
NSString* SQLValues=#"";
NSString* SQL=#"";
//Chekc Wheather Insert or update?
BOOL IsNew=NO;;
if([[objDic valueForKey:PrimaryKey] intValue]==0)
{
IsNew=YES;
}
NSArray* Keys=[objDic allKeys];
NSLog(#"%#",Keys);
if(IsNew)
{
for(int i=0;i<Keys.count;i++)
{
if(![[Keys objectAtIndex:i] isEqual:PrimaryKey])
{
SQLColumns=[NSString stringWithFormat:#"%#%#,",SQLColumns,[Keys objectAtIndex:i]];
SQLValues=[NSString stringWithFormat:#"%#?,",SQLValues];
}
}
if([SQLColumns length]>0)
{
SQLColumns=[SQLColumns substringToIndex:[SQLColumns length]-1];
SQLValues=[SQLValues substringToIndex:[SQLValues length]-1];
}
SQL=[NSString stringWithFormat:#"INSERT INTO %# (%#) Values(%#)",TABLE_NAME,SQLColumns,SQLValues];
}
else
{
for(int i=0;i<Keys.count;i++)
{
if(![[Keys objectAtIndex:i] isEqual:PrimaryKey])
{
SQLColumns=[NSString stringWithFormat:#"%#%#=?,",SQLColumns,[Keys objectAtIndex:i]];
}
}
if([SQLColumns length]>0)
{
SQLColumns=[SQLColumns substringToIndex:[SQLColumns length]-1];
}
SQL=[NSString stringWithFormat:#"UPDATE %# SET %# WHERE %#=?",TABLE_NAME,SQLColumns,PrimaryKey];
//NSLog(sql);
}
sqlite3_stmt *insert_statement=nil;
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &insert_statement, NULL) != SQLITE_OK) {
//NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
NSLog(#"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
int intBindIndex=1;
for(int i=0;i<Keys.count;i++)
{
if(![[Keys objectAtIndex:i] isEqual:PrimaryKey])
{
sqlite3_bind_text(insert_statement,intBindIndex,[[objDic valueForKey:[Keys objectAtIndex:i]] UTF8String],-1, SQLITE_STATIC);
intBindIndex++;
}
}
if(!IsNew)
{
sqlite3_bind_text(insert_statement,Keys.count,[[objDic valueForKey:PrimaryKey] UTF8String],-1, SQLITE_STATIC);
}
int result;
result=sqlite3_step(insert_statement);
if(IsNew)
{
[objDic setObject:[NSString stringWithFormat:#"%d",sqlite3_last_insert_rowid(database)] forKey:PrimaryKey];
}
sqlite3_finalize(insert_statement);
[pool release];
NSLog(#"result:%d",result);
if(result==SQLITE_DONE)
return YES;
else
return NO;
}
-(BOOL)deleteQuery:(NSString *)query
{
NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
[self initializeDatabase:DBNAME];
NSString* SQL=#"";
SQL=[NSString stringWithString:query];
sqlite3_stmt *insert_statement=nil;
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &insert_statement, NULL) != SQLITE_OK) {
//NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
NSLog(#"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
int result;
result=sqlite3_step(insert_statement);
sqlite3_finalize(insert_statement);
[pool release];
NSLog(#"result:%d",result);
if(result==SQLITE_DONE)
return YES;
else
return NO;
}
#end

SQLite Problem - Database path

I'm trying to select data from the database and I have the following code in place:
Code:
// Setup the database object
sqlite3 *database;
// Init the animals Array
list = [[NSMutableArray alloc] init];
NSLog(#"documents path: ", documentsDir);
NSLog(#"database path: ", databasePath);
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select route_name from Route";
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)];
// Add the animal object to the animals Array
//[list addObject:animal];
[list addObject:aName];
//[animal release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
I'm getting EXC_BAD_ACCESS error at the first IF statement. Anyone any thoughts.
Also in the NSLOG documentsDir and databasePath are blank.
I have the following code in ViewDidLoad:
-(void)viewDidLoad
{
// Setup some globals
databaseName = #"xxxxxxCoreData.sqlite";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDir = [documentPaths objectAtIndex:0];
documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
It looks like databasePath is not retained, so between the time that the view loads and your database code is run, it's already been released. If you want to keep those variables around, you need to change the last two lines to this:
documentsDir = [[documentPaths objectAtIndex:0] retain];
databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain];
And since you're doing this in viewDidLoad you should release them in viewDidUnload (set to nil in this method as well) and dealloc.