Saving a CNPostalAddress in Objective-C

1.5k views Asked by At

I have this code:

CNMutablePostalAddress *postalAddress = [[CNMutablePostalAddress alloc] init];
[postalAddress setCity:@"City"];

CNLabeledValue *city = [CNLabeledValue labeledValueWithLabel:CNPostalAddressCityKey value:postalAddress.city];

NSArray<CNLabeledValue<CNMutablePostalAddress *> *> *postalAddresses = @[city];

contact.postalAddresses = @[postalAddresses];

I don't know how I can do this conversion, because I need to pass an array to contact.postalAddress in the code. I have tried everything possible, but got nothing.

This code give me this exception:

*** Terminating app due to uncaught exception 'CNPropertyInvalidTypeException', reason: 'Labeled value (
"<CNLabeledValue: 0x12d5a14c0: identifier=080A5D1B-1F2D-4EE2-AB6F-BFAD523DA1C9, label=city, value=City>") has incorrect type __NSArrayI for key postalAddresses. It should be CNLabeledValue.'

How could I do this?

2

There are 2 answers

2
meaning-matters On BEST ANSWER

This creates a new postal address and adds it to the contact. This is what you want, right?

CNMutablePostalAddress *postalAddress = [[CNMutablePostalAddress alloc] init];
postalAddress.city = @"City";

CNLabeledValue *labeledValue = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:address];
contact.postalAddresses = @[labeledValue];
0
Roger C Lee On

This is the correct implementation.

CNMutablePostalAddress *postalAddress = [[CNMutablePostalAddress alloc] init];
postalAddress.street = @"1 Market Street";
postalAddress.city = @"Sydney";
postalAddress.postalCode = @"2000";
postalAddress.state = @"NSW";
CNLabeledValue *address = [CNLabeledValue labeledValueWithLabel:CNLabelWork value:postalAddress];
contact.postalAddresses = @[address];