开发者

Creating an AddressBook copy

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜