2016-05-20 30 views
3

我有這樣的代碼:的Objective-C:保存CNPostalAddress

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

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

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

    contact.postalAddresses = @[postalAddresses]; 

我不知道我該怎麼做這個轉換,是因爲我需要傳遞給contact.postalAddress像這樣的數組中的代碼。我嘗試了一切可能,但沒有。

此代碼給我這個例外:

*** 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.' 

我怎麼能這樣做?

+0

你想要做什麼轉換?保存和轉換是不同的事情,請更正標題或故事。 –

+0

我需要將「城市」保存在「contact.postalAddresses」中,但我需要在轉換之前進行轉換,否則應用程序將與異常一起崩潰。 @意思重大 – David

回答

3

這將創建一個新的郵政地址並將其添加到contact。這是你想要的,對吧?

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

CNLabeledValue *labeledValue = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:address]; 
contact.postalAddresses = @[labeledValue]; 
+0

Yees!非常感謝! :) @意思重大 – David

+0

@大衛很高興幫助!你也可以投票^這個答案,以防你不知道;-) –

2

這是正確的實現。

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];