如何将从Addressbook检索到的信息保存到NSUserDefaults?

时间:2010-09-15 08:13:42

标签: iphone objective-c xcode

我正在尝试使用PeoplePicker来检索联系人的姓名和地址,并将其存储到NSUserDefaults中,我最终希望在tableview上检索它。

我的问题是如何在NSUserDefaults中保存信息。 我使用过NSDictionary,但我没有取得任何进展。 所以我试图将数组保存到NSUserDefaults。

有人可以帮助我吗?

我的代码如下:

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier {

    // Only inspect the value if it's an address.
    if (property == kABPersonAddressProperty) {
        ABMutableMultiValueRef multiValue = ABRecordCopyValue(person, property);
        for(CFIndex i=0;i<ABMultiValueGetCount(multiValue);i++)
        {
            ABMultiValueRef multi = ABRecordCopyValue(person, property);

        // Set up an NSArray and copy the values in.
        NSArray *theArray = [(id)ABMultiValueCopyArrayOfAllValues(multi) autorelease];

        // Figure out which values we want and store the index.
        const NSUInteger theIndex = ABMultiValueGetIndexForIdentifier(multi, identifier);

        // Set up an NSDictionary to hold the contents of the array.
        NSDictionary *dictionary = [theArray objectAtIndex:theIndex];

        // Set up NSStrings to hold keys and values.  First, how many are there?
        const NSUInteger theCount = [dictionary count];
        NSString *keys[theCount];
        NSString *values[theCount];

        // Get the keys and values from the CFDictionary.  Note that because
        // we're using the "GetKeysAndValues" function, you don't need to
        // release keys or values.  It's the "Get Rule" and only applies to
        // CoreFoundation objects.
        [dictionary getObjects:values andKeys:keys];

        // Set the address label's text.
        NSString *address;
        address = [NSString stringWithFormat:@"%@, %@, %@",
                   [dictionary objectForKey:(NSString *)kABPersonAddressStreetKey],
                   [dictionary objectForKey:(NSString *)kABPersonAddressCityKey],
                   [dictionary objectForKey:(NSString *)kABPersonAddressCountryKey]];

        NSLog(@"%@", address);

        [self dismissModalViewControllerAnimated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }
    NSUserDefaults *locatie = [NSUserDefaults standardUserDefaults];
    CFRelease(multiValue);
}

    return NO;
}

1 个答案:

答案 0 :(得分:0)

[locatie setObject:yourObject forKey:@"YoureKey"];

如果您想存储地址,请使用:

[locatie setObject:adress forKey:@"adressKey"];

检索使用:

adress = [locatie valueForKey:@"adressKey"];

注意: 在这些示例中,locatie是:NSUserDefaults *locatie = [NSUserDefaults standardUserDefaults];