Create CNPostalAddress from known values

5k Views Asked by At

I am trying to create a CNPostalAddress with some strings in Objective-C. I have street address, city, state, zip and country values. I have tried the code below but it’s not working. Thanks for your valuable time.

CNPostalAddress *postalAddr = [[CNPostalAddress alloc] init];
postalAddr.street = [NSString stringWithFormat:@"%@ %@",street1,street2];// here, I am getting an error: Street property is read only.
2

There are 2 best solutions below

0
On

Create a CNMutablePostalAddress instead of a CNPostalAddress:

CNMutablePostalAddress *postalAddr = [[CNMutablePostalAddress alloc] init];
postalAddr.street = [NSString stringWithFormat:@"%@ %@", street1, street2];

CNMutablePostalAddress is a subclass of CNPostalAddress, so you can use it like a CNPostalAddress from this point onward.

0
On

The above answer rewritten in Swift:

let postalAddr = CNMutablePostalAddress()
postalAddr.street = String(format: "%@ %@", street1, street2)