1

I want to copy all iPhone address book contacts into an array and then write this array to a file. I have written the following code and connected it to a button, but when I tap this button my app crashed.

Please help me to solve this problem.

My Method:

-(NSString *)pathOfFile{
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingFormat:@"contacts.plist"];
}


-(IBAction)createAddressBookCopy{

    ABAddressBookRef addressBook = ABAddressBookCreate();

    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);

    NSMutableArray *masterList = [[NSMutableArray alloc] init];
    for (int i = 0; i < nPeople; i++) {
        ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, i);
        CFStringRef fName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
        CFStringRef lName = ABRecordCopyValue(ref, kABPersonLastNameProperty);
        NSString *contactFirstLast = [NSString stringWithFormat: @"%@", (NSString *)fName];

        CFRelease(fName);
        CFRelease(lName);
        [masterList addObject:contactFirstLast];
        [contactFirstLast release];
    }

    //self.list = masterList;
    [masterList writeToFile:[self pathOfFile] atomically:YES];

    [masterList release]; 

}  

**here i only saved the first name;

theChrisKent
  • 15,029
  • 3
  • 61
  • 62
Shahriar
  • 318
  • 3
  • 12
  • simulator showes the app icon with other app icons(home ascreen). – Shahriar Apr 18 '11 at 20:10
  • Please go through this link for more details.[Go though this link][1] [1]: http://stackoverflow.com/questions/14766351/how-to-create-a-addressbook-and-contacts/21827787#21827787 – SURESH SANKE Feb 17 '14 at 11:29

1 Answers1

0

Looking at your code:

NSString *contactFirstLast = [NSString stringWithFormat: @"%@", (NSString *)fName];
// ....
contactFirstLast release];  // this is wrong

When you created the contactFirstLast, you don't own it and you are releasing it. This is why your application is crashing.

Black Frog
  • 11,595
  • 1
  • 35
  • 66