Leaks with NSStirng - nsstring

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);
}

Related

PubNub framework in Apple Watch

I have been trying to manually import the PubNub Framework into my Apple Watch app. There are a lot of dependencies and frameworks that are used by PubNub that are not available on the watch (i.e. SystemConfiguration, CFNetworking, etc.). Is Apple Watch supported by PubNub? How do I get it to nicely import into my Apple Watch app?
Only a few modifications needs to be made. Replacing UIKit with WatchKit replacements:
TLDR:
Replace UIDevice with WKInterfaceDevice replacements
Replace [[UIDevice currentDevice] identifierForDevice] with UUID stored in NSUserDefaults
Replace UIApplicationWillEnterForegroundNotification and UIApplicationDidEnterBackgroundNotification with NSExtensionHostWillEnterForegroundNotification and NSExtensionHostDidEnterBackgroundNotification
Remove GZIP references
Detailed Explanation By File:
PNConfiguration.m:
- (NSString *)uniqueDeviceIdentifier {
#if TARGET_OS_WATCH
NSString *key = #"PNUserDefaultsUUIDKey";
NSString *uuid = [[NSUserDefaults standardUserDefaults] stringForKey:key];
if (!uuid) {
uuid = [[NSUUID UUID] UUIDString];
[[NSUserDefaults standardUserDefaults] setValue:uuid forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
}
return uuid;
#elif __IPHONE_OS_VERSION_MIN_REQUIRED
return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
return ([self serialNumber]?: [self macAddress]);
#endif
}
PNNetwork.m:
- (NSDictionary *)defaultHeaders {
NSString *device = #"iPhone";
NSString *osVersion = #"2.0";
#if TARGET_OS_WATCH
osVersion = [[WKInterfaceDevice currentDevice] systemVersion];
device = [[WKInterfaceDevice currentDevice] model];
#elif __IPHONE_OS_VERSION_MIN_REQUIRED
device = [[UIDevice currentDevice] model];
osVersion = [[UIDevice currentDevice] systemVersion];
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
NSOperatingSystemVersion version = [[NSProcessInfo processInfo]operatingSystemVersion];
NSMutableString *osVersion = [NSMutableString stringWithFormat:#"%#.%#",
#(version.majorVersion), #(version.minorVersion)];
if (version.patchVersion > 0) {
[osVersion appendFormat:#".%#", #(version.patchVersion)];
}
#endif
NSString *userAgent = [NSString stringWithFormat:#"iPhone; CPU %# OS %# Version",
device, osVersion];
return #{#"Accept":#"*/*", #"Accept-Encoding":#"gzip,deflate", #"User-Agent":userAgent,
#"Connection":#"keep-alive"};
}
PubNub+Core.m:
- (instancetype)initWithConfiguration:(PNConfiguration *)configuration
callbackQueue:(dispatch_queue_t)callbackQueue {
// Check whether initialization has been successful or not
if ((self = [super init])) {
#if DEBUG
[PNLog dumpToFile:YES];
#else
[PNLog dumpToFile:NO];
#endif
DDLogClientInfo([[self class] ddLogLevel], #"<PubNub> PubNub SDK %# (%#)",
kPNLibraryVersion, kPNCommit);
_configuration = [configuration copy];
_callbackQueue = callbackQueue;
[self prepareNetworkManagers];
_subscriberManager = [PNSubscriber subscriberForClient:self];
_clientStateManager = [PNClientState stateForClient:self];
_listenersManager = [PNStateListener stateListenerForClient:self];
_heartbeatManager = [PNHeartbeat heartbeatForClient:self];
[self addListener:self];
[self prepareReachability];
#if TARGET_OS_WATCH
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self selector:#selector(handleContextTransition:)
name:NSExtensionHostWillEnterForegroundNotification object:nil];
[notificationCenter addObserver:self selector:#selector(handleContextTransition:)
name:NSExtensionHostDidEnterBackgroundNotification object:nil];
#elif __IPHONE_OS_VERSION_MIN_REQUIRED
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self selector:#selector(handleContextTransition:)
name:UIApplicationWillEnterForegroundNotification object:nil];
[notificationCenter addObserver:self selector:#selector(handleContextTransition:)
name:UIApplicationDidEnterBackgroundNotification object:nil];
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
NSNotificationCenter *notificationCenter = [[NSWorkspace sharedWorkspace] notifiertionCenter];
[notificationCenter addObserver:self selector:#selector(handleContextTransition:)
name:NSWorkspaceWillSleepNotification object:nil];
[notificationCenter addObserver:self selector:#selector(handleContextTransition:)
name:NSWorkspaceSessionDidResignActiveNotification object:nil];
[notificationCenter addObserver:self selector:#selector(handleContextTransition:)
name:NSWorkspaceDidWakeNotification object:nil];
[notificationCenter addObserver:self selector:#selector(handleContextTransition:)
name:NSWorkspaceSessionDidBecomeActiveNotification object:nil];
#endif
}
return self;
}
PubNub+Core.m:
- (void)handleContextTransition:(NSNotification *)notification {
#if TARGET_OS_WATCH
if ([notification.name isEqualToString:NSExtensionHostDidEnterBackgroundNotification]) {
DDLogClientInfo([[self class] ddLogLevel], #"<PubNub> Did enter background execution context.");
}
else if ([notification.name isEqualToString:NSExtensionHostWillEnterForegroundNotification]) {
DDLogClientInfo([[self class] ddLogLevel], #"<PubNub> Will enter foreground execution context.");
}
#elif __IPHONE_OS_VERSION_MIN_REQUIRED
if ([notification.name isEqualToString:UIApplicationDidEnterBackgroundNotification]) {
DDLogClientInfo([[self class] ddLogLevel], #"<PubNub> Did enter background execution context.");
}
else if ([notification.name isEqualToString:UIApplicationWillEnterForegroundNotification]) {
DDLogClientInfo([[self class] ddLogLevel], #"<PubNub> Will enter foreground execution context.");
}
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
if ([notification.name isEqualToString:NSWorkspaceWillSleepNotification] ||
[notification.name isEqualToString:NSWorkspaceSessionDidResignActiveNotification]) {
DDLogClientInfo([[self class] ddLogLevel], #"<PubNub> Workspace became inactive.");
}
else if ([notification.name isEqualToString:NSWorkspaceDidWakeNotification] ||
[notification.name isEqualToString:NSWorkspaceSessionDidBecomeActiveNotification]) {
DDLogClientInfo([[self class] ddLogLevel], #"<PubNub> Workspace became active.");
}
#endif
}
PubNub+Core.m:
- (void)dealloc {
#if TARGET_OS_WATCH
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:NSExtensionHostWillEnterForegroundNotification
object:nil];
[notificationCenter removeObserver:self name:NSExtensionHostDidEnterBackgroundNotification
object:nil];
#elif __IPHONE_OS_VERSION_MIN_REQUIRED
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:UIApplicationWillEnterForegroundNotification
object:nil];
[notificationCenter removeObserver:self name:UIApplicationDidEnterBackgroundNotification
object:nil];
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
NSNotificationCenter *notificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
[notificationCenter removeObserver:self name:NSWorkspaceWillSleepNotification object:nil];
[notificationCenter removeObserver:self name:NSWorkspaceSessionDidResignActiveNotification
object:nil];
[notificationCenter removeObserver:self name:NSWorkspaceDidWakeNotification object:nil];
[notificationCenter removeObserver:self name:NSWorkspaceSessionDidBecomeActiveNotification
object:nil];
#endif
}
PubNub+Publish.m: where PNGZIP is used
NSData *publishData = nil;
if (compressed) {
#if !TARGET_OS_WATCH
NSData *messageData = [messageForPublish dataUsingEncoding:NSUTF8StringEncoding];
NSData *compressedBody = [PNGZIP GZIPDeflatedData:messageData];
publishData = (compressedBody?: [#"" dataUsingEncoding:NSUTF8StringEncoding]);
#else
NSLog(#"Tried to compress, but GZip is not available");
#endif
}

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];

Update field value of Sqlite database using Xcode

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

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.

Resources