How can I get the values I set for custom properties in AddressBook to persist?

核能气质少年 提交于 2019-12-11 16:07:08

问题


I have created a custom property in AddressBook named "Qref". I can check it's there using [ABPerson properties], and it's always there for any test app I write.

By the way, you can't remove custom properties, because [ABPerson removeProperties] hasn't been implemented. Let me know if it ever is, because I need to remove one whose name I mistyped.

I set a property value with this code.

ABPerson *p = <person chosen from a PeoplePicker>;
NSError *e;
if (![p setValue: aString forProperty:@"Qref" error:&e]) {
  [NSAlert alertWithError:e]runModal;
}

(I have never seen the alert yet, but sometimes get a heap of error messages in the console.) At this point I can navigate away from the person in the PeoplePicker and return to find the value correctly set. If I check [[ABAddressBook sharedAddressBook] hasUnsavedChanges] the result is NO, so clearly changing a custom property value doesn't count as a change, so I force a save by inserting dummy person (please suggest a better way), then executing

[[ABAddressBook sharedAddressBook] save];

The dummy person appears immediately in AddressBook if it is running, so something's right. But when I close my app and run it again, I find the values I set have gone. (MacOSX-Lion)


回答1:


I've been barking up the wrong trees. It's turning out that I couldn't save any properties, irrespective of whether they were custom ones or not. Then I wondered if it was something to do with code-signing, entitlements or iCloud, which is impenetrable jungle to me. It seems the person you get from a PeoplePicker isn't associated with any address book so [[ABAddressBook sharedAddressBook] save] will do nothing. You have to get your person from an ABAddressBook instance. Here's the skeleton of what works, without any error checking.

ABPerson *p = [[myPeoplePicker selectedRecords] objectAtIndex:0];
NSString *uid = p.uniqueId;
ABPerson *editablePerson = 
     (ABPerson*) [[ABAddressBook sharedAddressBook] recordForUniqueId:uid];
// Typecast because it returns an ABRecord. Can anyone improve?
[editablePerson setValue:@"ABCD" forProperty:@"Qref"]; // my custom property
[[ABAddressBook sharedAddressBook] save];


来源:https://stackoverflow.com/questions/10097179/how-can-i-get-the-values-i-set-for-custom-properties-in-addressbook-to-persist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!