My app crashes with "Program received EXC_BAD_ACCESS" error iphone - iphone

When my app launches from BACKGROUND , I am running a new thread to get AddresssBook data using notification center. Here is my code which shows how I call the method
-(void)appLaunchedFromBackground:(NSNotification *) notification {
// NSThread *backgroundThread; is my ivar
backgroundThread = [[NSThread alloc]initWithTarget:self selector:#selector(getUpdatedAddressBookData) object:nil];
[backgroundThread start];
}
-(void)getUpdatedAddressBookData {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
AddressBook *addBook = [[AddressBook alloc]init];
[addBook fetchAddressBookDataInBackground];
[addBook release];
[pool drain];
}
Here is my code for fetchAddressBookDataInBackground method
-(void)fetchAddressBookDataInBackground {
if (self.tempArray == nil) {
NSMutableArray *temp = [[NSMutableArray alloc]init];
self.tempArray = temp;
[temp release];
}
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *tempPeople = [[NSArray alloc]init];
tempPeople = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
APP_DELGATE.people = [NSArray arrayWithArray:tempPeople];
int peoCount = [APP_DELGATE.people count];
for (int i=0; i<peoCount; i++) {
ABRecordRef record = [APP_DELGATE.people objectAtIndex:i];
NSNumber *recordId = [NSNumber numberWithInteger:ABRecordGetRecordID(record)];
// Get fname, lname, company
NSString *fnm = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty) ;
NSString *lnm = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty) ;
NSString *comp = (NSString*)ABRecordCopyValue(record,kABPersonOrganizationProperty);
// Get Ph no
ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(record, kABPersonPhoneProperty);
NSArray *tempPhNos = (NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);
NSArray* phoneNumbers = [self getPhoneNoWithoutSymbols:tempPhNos];
NSString *strPhoneNos = [self getStringRepresentaionFromArray:phoneNumbers];
// Get emails
ABMultiValueRef emailProperty = ABRecordCopyValue(record, kABPersonEmailProperty);
NSArray* emails = (NSArray*)ABMultiValueCopyArrayOfAllValues(emailProperty);
NSString *strEmails = [self getStringRepresentaionFromArray:emails];
// Get URL
ABMultiValueRef urlProperty = ABRecordCopyValue(record, kABPersonURLProperty);
NSArray* urls = (NSArray*)ABMultiValueCopyArrayOfAllValues(urlProperty);
NSString *strURLs = [self getStringRepresentaionFromArray:urls];
// Get Address
ABMultiValueRef address=ABRecordCopyValue(record, kABPersonAddressProperty);
CFDictionaryRef dic=nil;
NSMutableArray *addressArray = [[NSMutableArray alloc]init];
for (int index=0; index<ABMultiValueGetCount(address); index++) {
dic=ABMultiValueCopyValueAtIndex(address, index);
NSString* labelName=(NSString*)ABMultiValueCopyLabelAtIndex(address, index);
if (labelName) {
NSString *street =(NSString*) CFDictionaryGetValue(dic, kABPersonAddressStreetKey);
NSString *city= (NSString*)CFDictionaryGetValue(dic, kABPersonAddressCityKey) ;
NSString *state= CFDictionaryGetValue(dic, kABPersonAddressStateKey);
NSString *country=CFDictionaryGetValue(dic, kABPersonAddressCountryKey);
NSString *zipcode=CFDictionaryGetValue(dic, kABPersonAddressZIPKey);
NSString *addressDetails=#"";
if (street) {
addressDetails=[NSString stringWithFormat:#"%# ",street];
}
if (city) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,city];
}
if (state) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,state];
}
if (country) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,country];
}
if (zipcode) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,zipcode];
}
[addressArray addObject:addressDetails];
}
[labelName release];
CFRelease(dic);
}
NSString *strAddress = [self getStringRepresentaionFromArray:addressArray];
// Get Notes
NSString *noteString=(NSString *)ABRecordCopyValue(record, kABPersonNoteProperty);
// Get Birthdate
NSDate *birthDate=(NSDate*)ABRecordCopyValue(record, kABPersonBirthdayProperty) ;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM dd yyyy"];
NSString *birthdateString = [formatter stringFromDate:birthDate];
[formatter release];
// Get user image
UIImage *image = nil;
if( ABPersonHasImageData( record ) ) {
NSData *imageData = (NSData*)ABPersonCopyImageData(record);
image = [UIImage imageWithData:imageData];
[imageData release];
}
NSString *fullName = [NSString stringWithFormat:#"%# %#",fnm,lnm];
// Create User object & add it to array
User *user = [[User alloc]initUserWithUniqID:recordId.intValue FirstName:fnm lastName:lnm compositeName:fullName company:comp phoneNumbers:strPhoneNos emails:strEmails urls:strURLs address:strAddress notes:noteString dob:birthdateString userImage:image];
[self.tempArray addObject:user];
CFRelease(phoneNumberProperty);
[tempPhNos release];
CFRelease(emailProperty);
[emails release];
CFRelease(urlProperty);
[urls release];
CFRelease(address);
[addressArray release];
[birthDate release];
[comp release];
[noteString release];
[lnm release];
[fnm release];
[user release];
}
[tempPeople release];
CFRelease(addressBook);
addressBook = nil;
self.tempArray = [NSMutableArray arrayWithArray:[self.tempArray sortedArrayUsingSelector:#selector(compare:)]];
APP_DELGATE.allUsersArray = self.tempArray;
NSDictionary *dic = [NSDictionary dictionaryWithObject:self.tempArray forKey:BATCH_DONE_KEY];
[[NSNotificationCenter defaultCenter] postNotificationName:BACKGROUND_WORK_DONE_NOTIFICATION object:self userInfo:dic];
}
-(NSMutableArray*)getPhoneNoWithoutSymbols:(NSArray*)array {
if (self.phNoArray == nil) {
NSMutableArray *temp = [[NSMutableArray alloc]init];
self.phNoArray = temp;
[temp release];
}
[self.phNoArray removeAllObjects];
for (NSString *str in array) {
[self.phNoArray addObject:[self getPhNo:str]];
}
return self.phNoArray;
}
-(NSString*)getPhNo:(NSString*)str {
NSString *str0 = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *str1 = [str0 stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *str2 = [str1 stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *str3 = [str2 stringByReplacingOccurrencesOfString:#"-" withString:#""];
return str3;
}
-(NSString*)getStringRepresentaionFromArray:(NSArray*)array {
return [array componentsJoinedByString:DELIMITER_SYMBOL];
}
But my app crashes with "Program received EXC_BAD_ACCESS" error at any line where I am using "ABRecordCopyValue" function . What I am missing? I am not getting whats wrong in my code?
I tried setting NSZombieEnabled = YES , but its not showing any message. Just saying "Program received EXC_BAD_ACCESS" at any line using ABRecordCopyValue function & in console I see (gdb) thats it.
Any knid of help is highly appreciated. Thanks.

Related

EXC_BAD_ACCESS in a simple code

I want to construct a string with an array of objects
for (int n=0; n<[friends count]; n++) {
User* friend = [friends objectAtIndex:n];
if (n>=[friends count]-1) {
NSString* param = [NSString stringWithFormat:#"{\"target_id\":\"dummy(%d)\"}", [friend uid]];
NSString* sf2 = [[NSString alloc]init];
sf2= [sf stringByAppendingString:param];
[sf release];
sf = [[NSString alloc]initWithString:sf2];
[sf2 release];
[param release];
}else{
NSString* param = [NSString stringWithFormat:#"{\"target_id\":\"dummy(%d)\"},", [friend uid]];
NSString* sf2 = [[NSString alloc]init];
sf2= [sf stringByAppendingString:param];
[sf release];
sf = [[NSString alloc]initWithString:sf2];
[sf2 release];
[param release];
}
}
I want to know what I'm doing wrong.
Thanks in advance!!
param is autoreleased object so you should not release it.
Edit:
//initialize sf here.
for (int n=0; n<[friends count]; n++) {
User* friend = [friends objectAtIndex:n];
if (n>=[friends count]-1) {
NSString* param = [NSString stringWithFormat:#"{\"target_id\":\"dummy(%d)\"}", [friend uid]];
sf = [sf stringByAppendingString:param];
}else{
NSString* param = [NSString stringWithFormat:#"{\"target_id\":\"dummy(%d)\"},", [friend uid]];
sf = [sf stringByAppendingString:param];
}
}
use this code.... comment [sf release] and [param release];
for (int n=0; n<[friends count]; n++) {
User* friend = [friends objectAtIndex:n];
if (n>=[friends count]-1) {
NSString* param = [NSString stringWithFormat:#"{\"target_id\":\"dummy(%d)\"}", [friend uid]];
NSString* sf2 = [[NSString alloc]init];
sf2= [sf stringByAppendingString:param];
//[sf release];
sf = [[NSString alloc]initWithString:sf2];
[sf2 release];
//[param release];
}else{
NSString* param = [NSString stringWithFormat:#"{\"target_id\":\"dummy(%d)\"},", [friend uid]];
NSString* sf2 = [[NSString alloc]init];
sf2= [sf stringByAppendingString:param];
//[sf release];
sf = [[NSString alloc]initWithString:sf2];
[sf2 release];
//[param release];
}
}
may this will help you

Potential leak of an object allocated in iphone

when i am analyze my project following code gives me leakage warning. is there any way to solve my memory leakage problem ?
warning :
Potential leak of an object allocated on line 38 and stored into 'addressBook'
Bellow is my code.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
m_tableDataArray = [[[NSMutableArray alloc] init]autorelease];
NSMutableArray *listDate = [[[NSMutableArray alloc] init]autorelease];
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *addresses = (NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSInteger addressesCount = [addresses count];
for (int i = 0; i < addressesCount; i++) {
ABRecordRef record = [addresses objectAtIndex:i];
NSString *firstName = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty);
if(firstName != nil && lastName != nil){
NSString *contactFirstLast = [NSString stringWithFormat: #"%# %#", firstName, lastName];
[listDate addObject:contactFirstLast];
}
[firstName release];
[lastName release];
}
m_tableDataArray = [[NSArray arrayWithArray:listDate] retain];
[addresses release];
addresses = nil;
[m_mainTable reloadData];
}
Thanks in adv...
Once you have finished using addressBook you need to release it using:
CFRelease(addressBook);
This should probably be placed at the end of your viewWillAppear: method.
Updated: There are a few unnecessary arrays and steps in your version of viewWillAppear:. I have cleaned it up a bit and fixed a potential memory leak.
Note: I haven't actually run this so double-check that it works correctly.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// I assume m_tableDataArray is an instance variable. If so, if the
// view appears multiple times it will result in a leak unless we
// release pre-existing instances first.
[m_tableDataArray release], m_tableDataArray = nil;
m_tableDataArray = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *addresses = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
for (ABRecordRef record in addresses) {
NSString *firstName = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty);
if(firstName != nil && lastName != nil){
NSString *contactFirstLast = [NSString stringWithFormat: #"%# %#", firstName, lastName];
[m_tableDataArray addObject:contactFirstLast];
}
[firstName release];
[lastName release];
}
[addresses release], addresses = nil;
CFRelease(addressBook);
[m_mainTable reloadData];
}

iphone+UIscrollview or to use uitableview to display image in matrix format

I want to display the image(which comes from webservice) the format such that the output in the screen appears like below image:-
Now the logic i had implemented is,i had added the image in uiscrollview.
with the below logic:-
for (int j=0;j<9;j++) {
for (int i=0; i<[mainRestaurantArray count];i++) {
if ([[[mainRestaurantArray objectAtIndex:i] valueForKey:#"Image"] isKindOfClass:[UIImage class]]) {
[CombineArray addObject:[mainRestaurantArray objectAtIndex:i]];
//NSLog(#"cnt=>%d array==>%#",cnt,[CombineArray objectAtIndex:cnt]);
UIButton* btn = [[UIButton alloc]init];
btn.tag = cnt;
btn.frame = CGRectMake(15+(cnt%5)*60, 15+(cnt/5)*60,Width,Height);
btn.backgroundColor = [UIColor greenColor];
[btn setBackgroundImage:[[CombineArray objectAtIndex:cnt] valueForKey:#"Image"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(Buttonclick:) forControlEvents:UIControlEventTouchUpInside];
[ScrlPhotos addSubview:btn];
[btn release];
cnt++;
}
}
[mainRestaurantArray release];
counter++;
[self urlcalled];//The function which calls the webservice
}
//}
ScrlPhotos.contentSize = CGSizeMake(320, ([CombineArray count]/5.0)*60+25);
The function which does the webservice is below:-
-(void)urlcalled{
#try
{
if (rangeDistance == nil) {
rangeDistance =#"100";
}
urlstring[0]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Gym&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[1]=[NSString stringWithFormat:#"http://www.google.com/maps?q=resort&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[2]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Tourist place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[3]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Hotels&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[4]=[NSString stringWithFormat:#"http://www.google.com/maps?q=shopping Mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[5]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Industries&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[6]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Shopping_mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[7]=[NSString stringWithFormat:#"http://www.google.com/maps?q=garden&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[8]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Religious Place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[9]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Restaurants&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
NSLog(#"conte==>%d urlstring[counter]==>%#",counter,urlstring[counter]);
NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlstring[counter]]];
str1 = [str substringFromIndex:9];
//NSLog(#"===>%#",str1);
NSArray *array = [str1 componentsSeparatedByString:#"overlays:"];
NSString *str2 = [array objectAtIndex:1];
NSString *finalUpperStr = [str2 substringFromIndex:21];
array1 = [finalUpperStr componentsSeparatedByString:#"},panel:"];
NSString *strF = [array1 objectAtIndex:0];
NSArray *arrayF = [strF componentsSeparatedByString:#"{id:"];
///////....................this object will change as require in for loop .............................//
mainRestaurantArray = [[NSMutableArray alloc] init];
for (int i=1; i<[arrayF count]-5; i++) {
NSString *strF12 = [arrayF objectAtIndex:i];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSArray *aryF23 = [strF12 componentsSeparatedByString:#"latlng:{"];
//NSLog(#"%#",[aryF23 objectAtIndex:1]);
NSString *strF23 = [aryF23 objectAtIndex:1];
NSArray *ar = [strF23 componentsSeparatedByString:#"},image:"];
//NSLog(#"%#",[ar objectAtIndex:0]);
NSString *strLat = [ar objectAtIndex:0];
NSArray *arrayLat = [strLat componentsSeparatedByString:#","];
NSString *strFLat = [[arrayLat objectAtIndex:0] substringFromIndex:4];
NSString *strLong = [[arrayLat objectAtIndex:1] substringFromIndex:4];
//NSLog(#"Lati = %# Longi = %#" , strFLat , strLong);
[dic setValue:strFLat forKey:#"Latitude"];
[dic setValue:strLong forKey:#"Longitude"];
NSString *strLAdd = [ar objectAtIndex:1];
NSArray *arrayLAdd = [strLAdd componentsSeparatedByString:#"laddr:"];
//NSLog(#"%#",[arrayLAdd objectAtIndex:1]);
NSString *strLAdd1 = [arrayLAdd objectAtIndex:1];
NSArray *arrayLAdd1 = [strLAdd1 componentsSeparatedByString:#"geocode:"];
// NSLog(#"%#",[arrayLAdd1 objectAtIndex:0]);
NSString *strAddres = [[arrayLAdd1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
//NSLog(#"%#",strAddres);
[dic setValue:strAddres forKey:#"Address"];
NSString *strName = [arrayLAdd1 objectAtIndex:1];
NSArray *arrayName = [strName componentsSeparatedByString:#"name:"];
NSString *strName1 = [[arrayName objectAtIndex:1]stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *arrayName1 = [strName1 componentsSeparatedByString:#"infoWindow:"];
[dic setValue:[arrayName1 objectAtIndex:0] forKey:#"Name"];
// for image load .. 07Dec..
NSString *strImage= [arrayF objectAtIndex:i];
NSRange range = [strImage rangeOfString:#"photoUrl"];
if(range.location == NSNotFound){
NSLog(#"Not found");
[dic setValue:#"" forKey:#"Image"];
}else{
NSArray *arrayImage = [strImage componentsSeparatedByString:#"photoUrl:"];
NSString *strImage1 = [arrayImage objectAtIndex:1];
NSArray *arrayImage1 = [strImage1 componentsSeparatedByString:#",photoType:"];
NSString *strfindImage = [[arrayImage1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strfindImage]]];
[dic setValue:myImage forKey:#"Image"];
}
[mainRestaurantArray addObject:dic];
if (i==20) {
break;
}
}
}
#catch (NSException * e)
{
NSLog(#"NSException==>%#",e);
}
}
But the problem i am facing is the image is displayed after completing the loop at 10 times.
I want to display the image parallely as it comes from webservice,so that time taken should be less..
Is there any way out..
Please help me.
Use UIImageView+cacheWeb.. it makes lazy loading a lot easier
http://hackemist.com/SDWebImage/doc/Categories/UIImageView+WebCache.html

iPhone - address book search crash

Some of our app store users are reporting a crash while searching their address book.
I'm pretty lost here cause I can't reproduce this issue.
Is there anything wrong with how I'm querying the address book ? Thanks!!
+ (NSDictionary *) scanAddressBook
{
#if TARGET_OS_IPHONE
NSUInteger i;
CFIndex index;
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *people = (NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
if ( people==nil || (people && ([people count] == 0)))
{
TRACE_LOG(#"scanAddressBook ", #"NO ADDRESS BOOK ENTRIES TO SCAN");
if(people) [people release];
CFRelease(addressBook);
return nil;
}
NSMutableArray *numbersArray = [NSMutableArray new];
NSMutableArray *mailsArray = [NSMutableArray new];
for ( i=0; i<[people count]; i++ )
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
ABRecordRef person = (ABRecordRef)[people objectAtIndex:i];
NSMutableDictionary *phoneDictionary = [NSMutableDictionary new];
CFStringRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
CFStringRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
NSString* log =[NSString stringWithFormat:#"-----CONTACT ENTRY -> %# : %#", firstName, lastName ];
TRACE_LOG(#"scanAddressBook",log);
NSString *userName = #"NoName";
if (firstName && lastName)
userName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
else if (firstName)
userName = [NSString stringWithFormat:#"%#", firstName];
else if (lastName)
userName = [NSString stringWithFormat:#"%#", lastName];
if(firstName) CFRelease(firstName);
if(lastName) CFRelease(lastName);
//
// Phone Numbers
//
ABMutableMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFIndex phoneNumberCount = ABMultiValueGetCount( phoneNumbers );
for ( index=0; index<phoneNumberCount; index++ )
{
CFStringRef phoneNumberLabel = ABMultiValueCopyLabelAtIndex( phoneNumbers, index);
CFStringRef phoneNumberValue = ABMultiValueCopyValueAtIndex( phoneNumbers, index);
CFStringRef phoneNumberLocalizedLabel = ABAddressBookCopyLocalizedLabel( phoneNumberLabel );
// converts "_$!<Work>!$_" to "work" and "_$!<Mobile>!$_" to "mobile"
// Find the ones you want here
//
NSString* log =[NSString stringWithFormat:#"-----PHONE ENTRY -> %# : %#", phoneNumberLocalizedLabel, phoneNumberValue ];
TRACE_LOG(#"scanAddressBook",log);
if (![NetworkingUtils validatePhoneNumber:(NSString *)phoneNumberValue]) {
NSLog(#"invalid phone number: %#",phoneNumberValue);
CFRelease(phoneNumberLocalizedLabel);
CFRelease(phoneNumberLabel);
CFRelease(phoneNumberValue);
continue;
}
[phoneDictionary setObject:(NSString *)phoneNumberValue forKey:InviteUserDataNumberKeyID];
[phoneDictionary setObject:(NSString *)phoneNumberLocalizedLabel forKey:InviteUserDataNumberTypeKeyID];
[phoneDictionary setObject:(NSString *)userName forKey:InviteUserDataNameTypeKeyID];
CFRelease(phoneNumberLocalizedLabel);
CFRelease(phoneNumberLabel);
CFRelease(phoneNumberValue);
NSMutableDictionary *copyPhoneDict = [phoneDictionary copy];
[numbersArray addObject:copyPhoneDict];
[copyPhoneDict release];
}
CFRelease(phoneNumbers);
[phoneDictionary release];
NSMutableDictionary *mailDictionary = [NSMutableDictionary new];
ABMutableMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex mailsNumberCount = ABMultiValueGetCount( emails );
for ( index=0; index < mailsNumberCount; index++ )
{
CFStringRef emailValue = ABMultiValueCopyValueAtIndex( emails,index);
// converts "_$!<Work>!$_" to "work" and "_$!<Mobile>!$_" to "mobile"
// Find the ones you want here
//
NSString* log =[NSString stringWithFormat:#"-----EMAIL ENTRY -> : %#", emailValue ];
TRACE_LOG(#"scanAddressBook",log);
if (![NetworkingUtils validateEmail:(NSString *)emailValue]) {
NSLog(#"invalid email address: %#",(NSString *)emailValue);
if (emailValue) {
CFRelease(emailValue);
}
continue;
}
[mailDictionary setObject:(NSString *)emailValue forKey:InviteUserDataMailKeyID];
[mailDictionary setObject:(NSString *)#"email" forKey:InviteUserDataMailTypeKeyID];
[mailDictionary setObject:(NSString *)userName forKey:InviteUserDataMailOwnerKeyID];
if (emailValue) {
CFRelease(emailValue);
}
NSMutableDictionary *copyMailDict = [mailDictionary copy];
[mailsArray addObject:copyMailDict];
[copyMailDict release];
}
if(emails) CFRelease(emails);
[mailDictionary release];
[pool drain];
}
NSString *countryCode = [[NSUserDefaults standardUserDefaults] objectForKey:RequestUserCountryCodeKeyID];
if (!countryCode) {
NSLocale *locale = [NSLocale currentLocale];
NSString *aCode = [locale objectForKey: NSLocaleCountryCode];
countryCode = [[NetworkingUtils codesByCountryCode] objectForKey:aCode];
}
NSDictionary *aDictionary = [NSDictionary dictionaryWithObjectsAndKeys: [[numbersArray copy] autorelease], InviteUsersNumbersArrayKeyID,
[[mailsArray copy] autorelease], InviteUsersMailsArrayKeyID,
countryCode, RequestUserCountryCodeKeyID, nil];
[numbersArray release];
[mailsArray release];
[people release];
CFRelease(addressBook);
return aDictionary;
#else
return nil ;
#endif
}
CFRelease() will crash if you provide a NULL value. I see most of your CFRelease() calls do check for NULL, but not all of them.
Most likely one of these is triggering the crash?
I'm not very familiar with ABAddressBook, so don't know in what situations they would return NULL.
On a related note, Objective-C's -release method does not crash on nil, so you may as well change: if(people) [people release]; to just [people release]; as all methods in Objective-C will silently do nothing if sent to a nil.

Memory Leak in TouchMXL?

I'm using TouchXML to parse an XML-stream the following way:
CXMLDocument *parser = [[CXMLDocument alloc] initWithXMLString:responseString options:0 error:nil];
[responseString release];
// array holding all the nodes
NSArray *directionNodes = [parser nodesForXPath:#"//direction" error:nil];
NSArray *linieNodes = [parser nodesForXPath:#"//route" error:nil];
NSArray *timeNodes = [parser nodesForXPath:#"//time" error:nil];
for (int i = 0; i < [directionNodes count]; i++) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
CXMLElement *direction = [directionNodes objectAtIndex:i];
CXMLElement *route = [linieNodes objectAtIndex:i];
CXMLElement *time = [timeNodes objectAtIndex:i];
// if rows are empty, stop it
if ([[direction stringValue] isEqualToString:#""]) {
break;
}
AbfahrtszeitResult *result = [[AbfahrtszeitResult alloc] init];
[result setLinie:[route stringValue]];
[result setZiel:[direction stringValue]];
[result setZeit:[time stringValue]];
[mutableAbfahrten addObject:result];
[result release];
[pool release];
}
Now, I always get a memory leak in the "stringValue"-line... am I doing something wrong or is it TouchXML?
Thanks a lot,
Stefan
-(NSString *) linie {
return linie;
}
- (void) setLinie:(NSString *)textValue {
[textValue retain];
[linie release];
linie = textValue;
}
-(NSString *) ziel {
return ziel;
}
-(void) setZiel:(NSString *)textValue {
[textValue retain];
[ziel release];
ziel = textValue;
}
-(NSString *) zeit {
return zeit;
}
-(void) setZeit:(NSString *)textValue {
[textValue retain];
[zeit release];
zeit = textValue;
}
+ (NSString *) cleanUpString:(NSString *) cleanme {
NSMutableString *tempString = [[NSMutableString alloc] initWithString:cleanme];
[tempString replaceOccurrencesOfString:#" " withString:#" " options:0 range:NSMakeRange(0, [tempString length])];
[tempString replaceOccurrencesOfString:#"&nbsp" withString:#" " options:0 range:NSMakeRange(0, [tempString length])];
return [tempString autorelease];
}
You have at least one leak when [[direction stringValue] isEqualToString:#""] is true as you break out of the for loop without releasing your AutoreleasePool. Beyond that, we'd need to see the implementation of your AbfahrtszeitResult class to see how your Linie setter is defined.