如何为MKPlacemark创建addressDictionary?

时间:2011-10-16 18:14:15

标签: objective-c ios5 mkannotation addressbook

    placemark = [[MKPlacemark alloc]initWithCoordinate:storedCoordinate addressDictionary:addressDict];

我尝试创建用于上面代码的字典,但没有任何作用:(

    NSDictionary *addressDict = [[NSDictionary alloc] initWithObjectsAndKeys:
    location.countryCode, @"CountryCode",
    location.country,@"kABPersonAddressCountryKey", 
    location.state, kABPersonAddressStateKey, 
    location.city, @"City",
    location.street, kABPersonAddressStreetKey,
    location.zip, kABPersonAddressZIPKey,
    nil];

2 个答案:

答案 0 :(得分:48)

为MKPlacemark创建addressDictionary时,建议您使用ABPerson中定义的“Address Property”常量。注意,由于这些常量是CFStringRef类型,因此您需要将它们转换为(NSString *),以便将它们用作NSDictionary中的键。

NSDictionary *addressDict = @{
                              (NSString *) kABPersonAddressStreetKey : location.street,
                              (NSString *) kABPersonAddressCityKey : location.city,
                              (NSString *) kABPersonAddressStateKey : location.state,
                              (NSString *) kABPersonAddressZIPKey : location.zip,
                              (NSString *) kABPersonAddressCountryKey : location.country,
                              (NSString *) kABPersonAddressCountryCodeKey : location.countryCode
                              };

iOS 9+更新:使用新的“联系人框架”

NSDictionary *addressDict = @{
                              CNPostalAddressStreetKey : location.street,
                              CNPostalAddressCityKey : location.city,
                              CNPostalAddressStateKey : location.state,
                              CNPostalAddressPostalCodeKey : location.zip,
                              CNPostalAddressCountryKey : location.country,
                              CNPostalAddressISOCountryCodeKey : location.countryCode
                              };

答案 1 :(得分:14)

值得注意的是,您需要将“AddressBook.framework”添加到项目构建设置中。 也可以在标题(.h文件)中导入:

#import <AddressBook/AddressBook.h>

然后在您的实现(.m文件)中,您可以使用:

(NSString*)kABPersonAddressStreetKey
(NSString*)kABPersonAddressCityKey
(NSString*)kABPersonAddressStateKey
(NSString*)kABPersonAddressCountryKey