0

Here is my code to get Notes from AddressBook.

 +(NSString*)getNote:(ABRecordRef)record {

  return ABRecordCopyValue(record, kABPersonNoteProperty);
}

But in above implementation I have memory leak. So to remove memory leak I wrote following code

    +(NSString*)getNote:(ABRecordRef)record {

    NSString *tempNotes = (NSString*)ABRecordCopyValue(record, kABPersonNoteProperty);
    NSString *notes = [NSString stringWithString:tempNotes];
    [tempNotes release];
    return notes;

}

If I write above code my app crashes. Whats going wrong? Thanks.

UPDATE: I call this method as follows :

notes = [AddreesBook getNote:record];

where notes is my ivar & I am releasing it in dealloc method.

iOSAppDev
  • 2,755
  • 4
  • 39
  • 77

2 Answers2

1

Your first implementation violates the ownership rule:

Memory Management Rules

Which is to say, the API call you're using contains "Copy", but you're treating it like an autoreleased object.

Given that you're returning an autoreleased object in your revised implementation, I suspect you're not retaining your returned note string. You'll be able to tell for sure if this is the case if when running under a debugger your app crashes in NSPopAutoreleasePool().

A simple test would be to send -retain to the note object you get back and see if the crash goes away:

NSString    *note = [ MyAddressBook getNote: abRecord ];

[ note retain ];
/* ... use note ... */

/* we retained the object, we must also release it when done with it. */
[ note release ];
more tension
  • 3,312
  • 17
  • 19
0

Assuming the record parameter is correctly set, the following should return an autoreleased NSString.

+ (NSString *)getNote:(ABRecordRef)record {
    return [(NSString *)ABRecordCopyValue(record, kABPersonNoteProperty) autorelease];
}

However, I'm not currently seeing why your current version of getNote isn't working.

mttrb
  • 8,297
  • 3
  • 35
  • 57