开发者

Creating an AddressBook copy

开发者 https://www.devze.com 2023-02-27 09:31 出处:网络
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 cra

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=NSSea开发者_JAVA百科rchPathForDirectoriesInDomains(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;


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.

0

精彩评论

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