开发者

iphone sqlite memory leak with [NSString stringWithUTF8String:(char*)sqlite3_column_text

开发者 https://www.devze.com 2023-01-23 20:47 出处:网络
I keep getting a memory leak indication from this sql statement when I assign the value retrieved from the database...

I keep getting a memory leak indication from this sql statement when I assign the value retrieved from the database...

Person *tmpPerson = [[Person alloc] init];

tmpPerson.personName = [NSString stringWithUTF8String:    (char*)sqlite3_column_text(SelectPersonStmt, 0)];
tmpPerson.personEmail = [NSString stringWithUTF8String:    (char*)sqlite3_column_text(SelectPersonStmt, 1)];

[personList addObject:tmpPerson];
[tmpPerson release];

However if i replace the nsobject class object ...tmpPerson with regular NSString's ...leaks doesn't complain anymore? Does anyone know why?

NSString * personName = [NSString stringWithUTF8String:(char*)sqlite3_column_text(SelectPersonStmt, 0)];
NSString * personEmail = [NSString stringWithUTF8String:(char*)sqlite3_column_text(SelectPersonStmt, 1)];

Here is my class definition ... is there anything wrong with it?

@interface Person : NSObject {

 NSString* personName;
 NSString* personMobile;
 NSString* personEmail;

}

@property (nonatomic, retain) NSString* personName, *personEmail, *personMobile;

- (id)init
{
  if ((self = [super init])) {  
    personName = [NSString string];
    personEmail = [NSString string];
    personMobile = [NSString string];
  }
  return self;
}

Am I missing something here ? Should I be even 开发者_StackOverflow中文版initializing these strings, it didn't seem to make any difference? I put them there incase i wanted to initialize them with some default value.

While testing this through instruments, i noticed that the memory leak is triggered during the deallocation method. I tried this and it didn't help either

-(void) dealloc

{
  personName = nil;
  personEmail = nil;
  [super dealloc];
}

Any help would be greatly appreciated. I've seen a lot of posts related to this but I'm not sure if folks are getting the same behavior I have mentioned.


You have to release your ivar in the dealloc:

-(void) dealloc
{ 
  [personName release];
  [personEmail release]; 
  [personMobile release];
  personName = nil; // Optionnal
  personEmail = nil; // Optionnal
  personMobile = nil; // Optionnal
  [super dealloc]; 
}


You should release the used strings in the Person struct, not setting it to NULL. Once you set it to NULL and there are no other objects referring to it, you have a leak, the system does not know how to reclaim it.

EDIT: damn, my answer came 10 seconds late :P

0

精彩评论

暂无评论...
验证码 换一张
取 消