Update field value of Sqlite database using Xcode - sqlite

I have an application with a save button. When I click on the save button, the application should automatically update the value of a row and set it to YES.
Till now I have the following code, but it isn't actually working. Keep in mind, my application is a tab menu application. In the first view I have the table cells, and on click I go to another view controller, a details view controller, where the button is present.
When I click on the button, the value of 'Fav' field in the database should change from NO to YES.
This is my code:
- (IBAction)AddButClick:(UIButton *)sender {
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateSelected];
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateHighlighted];
Favo = [[NSMutableArray alloc] initWithCapacity:1000000];
// NSLog(authorNAme);
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"dictionary.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"authorsDb2.sqlite"];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"FinalDb.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"xxJuridique-FINAL-OK.sqlite"];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"data.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %#", sqlite3_errmsg(db));
}
sqlite3_stmt *compiled_statement1;
if(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK) {
//const char *sqlStatement =
NSString *formatedSql = [NSString stringWithFormat:#"UPDATE Sheet1 SET Fav = 'YES' WHERE field3 = '%#' " , authorNAme2];
NSLog(#"This is the query %#",formatedSql);
const char *sql = [formatedSql UTF8String];
NSLog(#" !!!!!!!! In the middle of it !!!!!!!!!!!!");
if (sqlite3_prepare_v2(db, sql, -1, &compiled_statement1, NULL) != SQLITE_OK) {
NSLog(#"!!!!!!!!!!!!!!!!!!!ERRRRROOOOOOORRRRRRRRR!!!!!!!!!!!!!!!!!!!!!!!!!");
NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(db));
}
// sqlite3_exec(db, [compiled_statement1 UTF8String], NULL, NULL, NULL);
//sqlite3_bind_text(compiled_statement1, 1, [formatedSql UTF8String], -1, SQLITE_TRANSIENT);
int success = sqlite3_step(compiled_statement1);
sqlite3_reset(compiled_statement1);
if (success != SQLITE_ERROR) {
NSLog(#"Successfully inserted");
sqlite3_last_insert_rowid(db);
}
sqlite3_finalize(compiled_statement1);
}
//
// BOOL success = [fileMgr fileExistsAtPath:dbPath];
//
// if(!success)
// {
// NSLog(#"Cannot locate database file '%#'.", dbPath);
// }
// if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
// {
// NSLog(#"An error has occured: %#", sqlite3_errmsg(db));
//
// }
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql = "SELECT * FROM Sheet1";
NSLog(#"Successfully selected from database");
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
NSLog(#"Got in the else tag");
while (sqlite3_step(sqlStatement)==SQLITE_ROW /*&& PAss == NO*/) {
NSLog(#"Got in the while tag");
Author * author = [[Author alloc] init];
NSLog(#"Author initialized");
author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,10)];
NSLog(#"Initialization ok");
// NSLog(author.name);
if(/*author.name == #"NO" &&*/ HighLighted == NO){
//const char *sql2 = "INSERT INTO Sheet1 ";
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateNormal];
NSLog(#"We have not selected it as fav yet");
// [AddBut setSelected:NO]; //btn changes to normal state
NSLog(#"The button was NOt highlighted and now is");
HighLighted = YES;
// PAss = YES;
// [self release];
break;
}
else
{
NSLog(#"We have selected it as fav");
[AddBut setImage:[UIImage imageNamed:#"apple-logo.png"] forState:UIControlStateNormal];
[AddBut setSelected:NO]; //btn changes to normal state
NSLog(#"The button was highlighted and now is NOt");
HighLighted = NO;
break;
// [self viewDidLoad];
// PAss = YES;
}
// [Favo release];
// NSLog(Favo);
// author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
// author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
// author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)];
// [theauthors addObject:author];
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
// sqlite3_finalize(sqlStatement);
sqlite3_close(db);
return Favo;
}

The problem was not in the add but click, it was actually in the viewWillAppear, in which i should have done :
[self authorList2];
[self.tableView reloadData] ;
In order to load the mutable array and then reload data

Related

Failure to create two sibling nodes in the root node using libxml2 writer handler

I am new to libxml2 trying to generate XML files for the first time. But unable to create sibling node in the root node when try to create an XML file via testWriter.c link,The libxml2 will print an error message.
I want to create this example xml file. The point that there are sibling nodes in the root node:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<!--child1 comment-->
<child1>
<element11>value11</element11>
<element11>12</element11>
</child1>
<!--child2 comment-->
<child2>
<element21>value21</element21>
<element22>22</element22>
</child2>
</root>
My writer handler code:
static void
gen_child1(xmlTextWriterPtr writer) {
char buf[64];
// comment
xmlTextWriterWriteComment(writer, BAD_CAST "child1 comment");
// start
if( xmlTextWriterStartElement(writer, BAD_CAST "child1") < 0 )
return;
// add a child element
xmlTextWriterWriteElement(writer, BAD_CAST "element11", BAD_CAST "value11");
// add a child element
(void) snprintf(buf, sizeof buf, "%d", 12);
xmlTextWriterWriteElement(writer, BAD_CAST "element12", BAD_CAST buf);
// start new node
if( xmlTextWriterStartElement(writer, BAD_CAST "element13") < 0 )
return;
xmlTextWriterWriteElement(writer, BAD_CAST "element131", BAD_CAST "value131");
// end new node
xmlTextWriterEndElement(writer);
// end
xmlTextWriterEndElement(writer);
}
static void
gen_child2(xmlTextWriterPtr writer) {
char buf[64];
// comment
xmlTextWriterWriteComment(writer, BAD_CAST "child2 comment");
// start
if( xmlTextWriterStartElement(writer, BAD_CAST "child2") < 0 )
return;
// add a child element
xmlTextWriterWriteElement(writer, BAD_CAST "element21", BAD_CAST "value21");
// add a child element
(void) snprintf(buf, sizeof buf, "%d", 22);
xmlTextWriterWriteElement(writer, BAD_CAST "element22", BAD_CAST buf);
// start new node
if( xmlTextWriterStartElement(writer, BAD_CAST "element23") < 0 )
return;
xmlTextWriterWriteElement(writer, BAD_CAST "element231", BAD_CAST "value231");
// end new node
xmlTextWriterEndElement(writer);
// end
xmlTextWriterEndElement(writer);
}
static void
gen_doc(void) {
xmlTextWriterPtr writer = NULL;
xmlDocPtr doc;
xmlNodePtr root;
if( !(doc = xmlNewDoc(BAD_CAST XML_DEFAULT_VERSION)) )
puts("xmlNewDoc() failure");
if( !(root = xmlNewDocNode(doc, NULL, BAD_CAST "root", NULL)) )
puts("xmlNewDocNode() failure");
xmlDocSetRootElement(doc, root);
// create writer
if( !(writer = xmlNewTextWriterTree(doc, root, 0)) )
puts("xmlNewTextWriterTree() failure");
// start doc
if( xmlTextWriterStartDocument(writer, NULL, ENCODING, NULL) < 0 )
puts("xmlTextWriterStartDocument() failure");
gen_child1(writer);
gen_child2(writer);
// end doc
xmlTextWriterEndDocument(writer);
// free writer
xmlFreeTextWriter(writer);
print_doc(doc);
}
Libxml2 print this error message:
# This is Libxml2 output:
Entity: line 2: parser error : Extra content at the end of the document
nt13><element131>value131</element131></element13></child1><!--child2 comment-->
^
error : xmlTextWriterWriteDocCallback : XML error 5 !
I/O error : flush error
error : xmlTextWriterCloseDocCallback : XML error 5 !
# This is my print_doc(doc) output:
Length: 224
<?xml version="1.0" encoding="UTF-8"?>
<root><!--child1 comment--><child1><element11>value11</element11><element12>12</element12><element13><element131>value131</element131></element13></child1></root>
<!--child2 comment-->
I will succeed without using the writer handler, this the code:
static xmlNodePtr
gen_child1(xmlNsPtr _ns, const xmlChar *_name) {
xmlNodePtr retval = xmlNewNode(_ns, _name);
char buf[64];
if( retval ) {
xmlNewTextChild(retval, _ns, BAD_CAST "element11", BAD_CAST "value11");
(void) snprintf(buf, sizeof buf, "%d", 12);
xmlNewTextChild(retval, _ns, BAD_CAST "element11", BAD_CAST buf);
}
return retval;
}
static xmlNodePtr
gen_child2(xmlNsPtr _ns, const xmlChar *_name) {
xmlNodePtr retval = xmlNewNode(_ns, _name);
char buf[64];
if( retval ) {
xmlNewTextChild(retval, _ns, BAD_CAST "element21", BAD_CAST "value21");
(void) snprintf(buf, sizeof buf, "%d", 22);
xmlNewTextChild(retval, _ns, BAD_CAST "element22", BAD_CAST buf);
}
return retval;
}
static void
gen_doc(void) {
xmlTextWriterPtr writer = NULL;
xmlDocPtr doc;
xmlNodePtr root;
if( !(doc = xmlNewDoc(BAD_CAST XML_DEFAULT_VERSION)) )
puts("xmlNewDoc() failure");
if( !(root = xmlNewDocNode(doc, NULL, BAD_CAST "root", NULL)) )
puts("xmlNewDocNode() failure");
xmlDocSetRootElement(doc, root);
xmlAddChild(root, xmlNewComment(BAD_CAST "child1 comment"));
xmlAddChild(root, gen_child1(NULL, BAD_CAST "child1"));
xmlAddChild(root, xmlNewComment(BAD_CAST "child2 comment"));
xmlAddChild(root, gen_child2(NULL, BAD_CAST "child2"));
print_doc(doc);
xmlFreeDoc(doc);
}
I want to know what i did wrong when using the writer handler?
xmlNewTextWriterTree has never been implemented correctly in libxml2.
The xmlTextWriter API should only be used to write documents in serialized form. Functions like xmlNewTextWriterTree or xmlNewTextWriterDoc serialize and reparse XML which is really inefficient. It's better to build documents using the "tree" API like in your working example.
You could open a bug report, but this badly designed part of the code base is unlikely to get fixed.

Update Sqlite database only works once

I have an sqlite database and it's loaded into a tableview, now when i click a row to see its details..i go to another view controller in which details are displayed and a AddToFav button exists.
When i click it..and go to another view controller...i can see the changes correctly, my database is updating correctly, but if i try to add another entry..i notice that my database is not updated anymore..The addToFav button only updates the database once. Any ideas?
This is my Addbut IBaction :
- (IBAction)AddButClick:(UIButton *)sender {
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateSelected];
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateHighlighted];
Favo = [[NSMutableArray alloc] initWithCapacity:1000000];
#try {
// NSFileManager *fileMgr = [NSFileManager defaultManager];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"dictionary.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"authorsDb2.sqlite"];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"FinalDb.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"xxJuridique-FINAL-OK.sqlite"];
// [self createEditableCopyOfDatabaseIfNeeded];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"data.sqlite"];
// [self.tableView reloadData];
sqlite3_stmt *compiled_statement1;
if(sqlite3_open([PathDB UTF8String], &db) == SQLITE_OK) {
// UIAlertView *DbO = [[UIAlertView alloc]
// initWithTitle:#"PATH" message:#"Database still open !" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
//
// [DbO show];
NSString *formatedSql = [NSString stringWithFormat:#"UPDATE Sheet1 SET Fav = 'YES' WHERE field3 = '%#'" , authorNAme2];
// UIAlertView *messageAlert = [[UIAlertView alloc]
// initWithTitle:#"Query" message:formatedSql delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
//
// [messageAlert show];
//
UIAlertView *PAth = [[UIAlertView alloc]
initWithTitle:#"PATH" message:PathDB delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[PAth show];
// NSLog(PathDB);
const char *sql = [formatedSql UTF8String];
NSLog(#" !!!!!!!! In the middle of it !!!!!!!!!!!!");
if (sqlite3_prepare_v2(db, sql, -1, &compiled_statement1, NULL) != SQLITE_OK) {
NSLog(#"!!!!!!!!!!!!!!!!!!!ERRRRROOOOOOORRRRRRRRR!!!!!!!!!!!!!!!!!!!!!!!!!");
//NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
NSLog(#"This is the query %#",formatedSql);
}
// sqlite3_bind_text(compiled_statement1, 1, [authorNAme2 UTF8String], -1, SQLITE_TRANSIENT);
int success = sqlite3_step(compiled_statement1);
// sqlite3_reset(compiled_statement1);
if (success != SQLITE_ERROR) {
NSLog(#"Successfully inserted");
sqlite3_last_insert_rowid(db);
}
//
// BOOL success = [fileMgr fileExistsAtPath:dbPath];
//
// if(!success)
// {
// NSLog(#"Cannot locate database file '%#'.", dbPath);
// }
// if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
// {
// NSLog(#"An error has occured: %#", sqlite3_errmsg(db));
//
// }
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql = "SELECT * FROM Sheet1";
NSLog(#"Successfully selected from database");
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
NSLog(#"Got in the else tag");
while (sqlite3_step(sqlStatement)==SQLITE_ROW /*&& PAss == NO*/) {
NSLog(#"Got in the while tag");
Author * author = [[Author alloc] init];
NSLog(#"Author initialized");
author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,10)];
NSLog(#"Initialization ok");
// NSLog(author.name);
if(/*author.name == #"NO" &&*/ HighLighted == NO){
//const char *sql2 = "INSERT INTO Sheet1 ";
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateNormal];
NSLog(#"We have not selected it as fav yet");
// [AddBut setSelected:NO]; //btn changes to normal state
NSLog(#"The button was NOt highlighted and now is");
HighLighted = YES;
break;
}
else
{
NSLog(#"We have selected it as fav");
[AddBut setImage:[UIImage imageNamed:#"apple-logo.png"] forState:UIControlStateNormal];
[AddBut setSelected:NO]; //btn changes to normal state
NSLog(#"The button was highlighted and now is NOt");
HighLighted = NO;
break;
// [self viewDidLoad];
// PAss = YES;
}
// [Favo release];
// NSLog(Favo);
// author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
// author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
// author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)];
// [theauthors addObject:author];
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
// sqlite3_finalize(sqlStatement);
// sqlite3_close(db);
UIAlertView *fin = [[UIAlertView alloc]
initWithTitle:#"Query" message:#"DOne with Click Button" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[fin show];
return Favo;
}
Thank you #crazyCreator for your answer !!!!
[self authorList2];
[self.tableView reloadData];

Unused variable question

I have the following code in the implementation file:
#import "Possession.h"
#implementation Possession
#synthesize possessionName,serialNumber, valueInDollars, dateCreated;
+ (id)randomPossession
{
// Create an array of three adjectives
NSArray *randomAdjectiveList = [NSArray arrayWithObjects:#"Fluffy",
#"Rusty",
#"Shiny", nil];
// Create an array of three nouns
NSArray *randomNounList = [NSArray arrayWithObjects:#"Bear",
#"Spork",
#"Mac", nil];
// Get the index of a random adjective/noun from the lists
// Note: The % operator, called the modulo operator, gives
// you the remainder. So adjectiveIndex is a random number
// from 0 to 2 inclusive.
unsigned long adjectiveIndex = rand() % [randomAdjectiveList count];
unsigned long nounIndex = rand() % [randomNounList count];
NSString *randomName = [NSString stringWithFormat:#"%# %#",
[randomAdjectiveList objectAtIndex:adjectiveIndex],
[randomNounList objectAtIndex:nounIndex]];
int randomValue = rand() % 100;
NSString *randomSerialNumber = [NSString stringWithFormat:#"%c%c%c%c",
'O' + rand() % 10,
'A' + rand() % 26,
'O' + rand() % 10,
'A' + rand() % 26,
'O' + rand() % 10];
// Once again, ignore the memory problems with this method
Possession *newPossession =
[[self alloc] initWithPossessionName:randomName
valueInDollars:randomValue
serialNumber:randomSerialNumber];
return newPossession;
return [newPossession autorelease];
}
- (id) initWithPossessionName:(NSString *)name
valueInDollars:(int)value
serialNumber:(NSString *)sNumber
{
// Call the superclass's designated initializer
[super init];
// Give the instance variables initial values
[self setPossessionName:name];
[self setSerialNumber:sNumber];
[self setValueInDollars:value];
dateCreated = [[NSDate alloc] init];
// Return the address of the newly initialized object
return self;
}
- (id) init
{
return [self initWithPossessionName:#"Possession"
valueInDollars:0
serialNumber:#""];
}
- (NSString *)description;
{
NSString *descriptionString =
[[NSString alloc] stringWithFormat:#"%# (%#): Worth $%d, recorded on %#",
possessionName,
serialNumber,
valueInDollars,
dateCreated];
}
- (void) dealloc
{
[possessionName release];
[serialNumber release];
[dateCreated release];
[super dealloc];
}
#end
For the descriptionString, I am getting an unused variable error, and for the line which reads "dateCreated],", I am getting a Thread 1: Program received signal: "SIGABRT" error which opens up the debugger. For the line immediately following, I am receiving a Control reaches end of non-void function error.
Here is the header file:
#import <Foundation/Foundation.h>
#interface Possession : NSObject {
NSString *possessionName;
NSString *serialNumber;
int valueInDollars;
NSDate *dateCreated;
}
+ (id)randomPossession;
- (id)initWithPossessionName:(NSString *)name
valueInDollars:(int)value
serialNumber:(NSString *)number;
- (id) init;
#property (nonatomic, copy) NSString *possessionName;
#property (nonatomic, copy) NSString *serialNumber;
#property (nonatomic) int valueInDollars;
#property (nonatomic, readonly) NSDate *dateCreated;
#end
Here is the main file:
#import <Foundation/Foundation.h>
#import "Possession.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// Create a mutable array, store its address in items variable
NSMutableArray *items = [[NSMutableArray alloc] init];
for(int i = 0; i < 10; i++) {
Possession *p = [Possession randomPossession];
[items addObject:p];
}
for (int i = 0; i < [items count]; i++)
NSLog(#"%#", [items objectAtIndex:i]);
[items release];
// Don't leave items pointed at freed memory!
items = nil;
[pool drain];
return 0;
}
For the description method,
the local variable descriptionString is never used other then being created.
it's a non-void method and you never return anything
The SIGABRT is likely to be caused by one of the possessionName, serialNumber, valueInDollars, dateCreated being nil.

Memory leaks While fetching data from Sqlite

Iam getting memory leaks in below code.
Is this is the proper way to handle memory?
Please do correct me.
-(void)getholidays
{
if (idarray!=nil) {
[idarray release];
idarray=nil;
}
idarray=[[NSMutableArray alloc]init];
if (Countryarray!=nil) {
[Countryarray release];
Countryarray=nil;
}
Countryarray =[[NSMutableArray alloc] init];
if (Holidaynamearray!=nil) {
[Holidaynamearray release];
Holidaynamearray=nil;
}
Holidaynamearray =[[NSMutableArray alloc] init];
if (Datearray!=nil) {
[Datearray release];
Datearray=nil;
}Datearray =[[NSMutableArray alloc] init];
if (Dayarray!=nil) {
[Dayarray release];
Dayarray=nil;
}Dayarray =[[NSMutableArray alloc] init];
if (Favoritearray!=nil) {
[Favoritearray release];
Favoritearray=nil;
}
Favoritearray =[[NSMutableArray alloc] init];
NSString *destinationPath = [self getdestinationPath];
const char *dbpath = [destinationPath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL;
NSDate *today = [NSDate date];
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"MMMM-dd-yyyy"];
NSString *Todaystrng = [formatter stringFromDate:today];
NSLog(#"today date %#",Todaystrng);
querySQL=[NSString stringWithFormat:#"SELECT * FROM Holiday_Table WHERE CountryName in (SELECT Country_Name from Country WHERE Country_Selected =1) ORDER BY Date ASC "];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSLog(#"success");
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *idstringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
NSString *countrynamestringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
NSString *holidaynamestringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];
NSString *datestringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)];
//Below line gets leaking
NSString *daystringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 4)];
//Belowline gets leaking
NSString *favoritestringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 5)];
[idarray addObject:idstringfromdb];
[idstringfromdb release];
idstringfromdb=nil;
[Countryarray addObject:countrynamestringfromdb];
[countrynamestringfromdb release];
countrynamestringfromdb=nil;
[Holidaynamearray addObject:holidaynamestringfromdb];
[holidaynamestringfromdb release];
holidaynamestringfromdb=nil;
[Datearray addObject:datestringfromdb];
[datestringfromdb release];
datestringfromdb=nil;
[Dayarray addObject:daystringfromdb];
[daystringfromdb release];
daystringfromdb=nil;
[Favoritearray addObject:favoritestringfromdb];
[favoritestringfromdb release];
favoritestringfromdb=nil;
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
As far as I can tell from your code the leak happens because of addObject to the array (which increases the retain count by one) make sure that when you remove the object and are done with it from the array you release it there as well.

Leaks with NSStirng

Iam getting memory leaks in below code.
Is this is the proper way to handle memory?
Please do correct me.
-(void)getholidays
{
if (idarray!=nil) {
[idarray release];
idarray=nil;
}
idarray=[[NSMutableArray alloc]init];
if (Countryarray!=nil) {
[Countryarray release];
Countryarray=nil;
}
Countryarray =[[NSMutableArray alloc] init];
if (Holidaynamearray!=nil) {
[Holidaynamearray release];
Holidaynamearray=nil;
}
Holidaynamearray =[[NSMutableArray alloc] init];
if (Datearray!=nil) {
[Datearray release];
Datearray=nil;
}Datearray =[[NSMutableArray alloc] init];
if (Dayarray!=nil) {
[Dayarray release];
Dayarray=nil;
}Dayarray =[[NSMutableArray alloc] init];
if (Favoritearray!=nil) {
[Favoritearray release];
Favoritearray=nil;
}
Favoritearray =[[NSMutableArray alloc] init];
NSString *destinationPath = [self getdestinationPath];
const char *dbpath = [destinationPath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL;
NSDate *today = [NSDate date];
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"MMMM-dd-yyyy"];
NSString *Todaystrng = [formatter stringFromDate:today];
NSLog(#"today date %#",Todaystrng);
querySQL=[NSString stringWithFormat:#"SELECT * FROM Holiday_Table WHERE CountryName in (SELECT Country_Name from Country WHERE Country_Selected =1) ORDER BY Date ASC "];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSLog(#"success");
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *idstringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
NSString *countrynamestringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
NSString *holidaynamestringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];
NSString *datestringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)];
//Below line gets leaking
NSString *daystringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 4)];
//Belowline gets leaking
NSString *favoritestringfromdb=[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 5)];
[idarray addObject:idstringfromdb];
[idstringfromdb release];
idstringfromdb=nil;
[Countryarray addObject:countrynamestringfromdb];
[countrynamestringfromdb release];
countrynamestringfromdb=nil;
[Holidaynamearray addObject:holidaynamestringfromdb];
[holidaynamestringfromdb release];
holidaynamestringfromdb=nil;
[Datearray addObject:datestringfromdb];
[datestringfromdb release];
datestringfromdb=nil;
[Dayarray addObject:daystringfromdb];
[daystringfromdb release];
daystringfromdb=nil;
[Favoritearray addObject:favoritestringfromdb];
[favoritestringfromdb release];
favoritestringfromdb=nil;
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}

Resources