2011-10-16 22 views
27
placemark = [[MKPlacemark alloc]initWithCoordinate:storedCoordinate addressDictionary:addressDict]; 

我試圖創建字典上面使用的代碼,但沒有任何工程:(如何爲MKPlacemark創建addressDictionary?

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

該國主要是在引號,但不應該。看[這個問題](http://stackoverflow.com/q/1923525/467105)。 – Anna

+0

我只是顯示不同的變體,他們都不工作 – Shmidt

+0

你能描述更多它不起作用嗎?例如,如果它崩潰什麼是錯誤信息?如果不是崩潰,那究竟是什麼?在init之後你如何處理地標變量? – Anna

回答

44

在創建addressDictionary爲MKPlacemark,我們建議您使用「地址屬性」常量中定義ABPerson注意,因爲這些常量是類型CFStringRef的,所以你需要將它們以使用它們作爲NSDictionary的內鍵強制轉換爲(的NSString *)。

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

Updat E對於iOS的9+:使用新的聯繫人框架

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

如果您使用的是ARC,您需要在演員表中添加'__bridge',如: '(__bridge NSString *)kABPersonAddressStreetKey:location.street' –

+2

什麼是apiummy api –

+0

不要忘記#import (<= 8.x) #import (> = 9.x) – user3589771

14

值得關注的是,你需要將「AddressBook.framework」添加到你的項目構建設置。 在你的頭還進口(h文件):

#import <AddressBook/AddressBook.h> 

然後在你的實現(.m文件),可以使用:

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

很好的說明, –

+0

導入聲明是解決我的問題的關鍵。 –