2012-04-01 60 views
3

我使用ABPeoplePickerNavigationController讓用戶選擇一個地址。在模擬器中一切正常。但是如果一個地址包含像「ü」這樣的非ASCII字符,我的設備上的結果會很奇怪。我有這樣的代碼:NSString似乎殺死Unicode字符

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier { 

ABMultiValueRef addressesMultiValue = ABRecordCopyValue(person, property); 
NSArray *addresses = (__bridge_transfer NSArray*)ABMultiValueCopyArrayOfAllValues(addressesMultiValue); 
CFRelease(addressesMultiValue); 

NSDictionary *addressData = [addresses objectAtIndex:0]; 

NSLog(@"%@", addressData); 

NSArray *addressKeys = [[NSArray alloc] initWithObjects:(NSString*)kABPersonAddressStreetKey, 
         (NSString*)kABPersonAddressZIPKey, 
         (NSString*)kABPersonAddressCityKey, 
         (NSString*)kABPersonAddressStateKey, 
         (NSString*)kABPersonAddressCountryKey, 
         (NSString*)kABPersonAddressCountryCodeKey, nil]; 

NSMutableString *address = [[NSMutableString alloc] init]; 

for (NSString *key in addressKeys) { 
    NSString *object = [addressData objectForKey:key]; 
    if (object) { 
     [address appendFormat:@"%@, ", object]; 
    } 
} 

NSLog(@"%@", address); 

爲addressData的輸出是這樣的:

{ 
City = "M\U00fcnchen"; 
Country = Deutschland; 
CountryCode = de; 
Street = "Some street"; 
ZIP = 81000; 
} 

和輸出的地址是:

Some street, 81000, München, Deutschland, de, 

的地址正確的輸出將是「一些81000,慕尼黑,德國,德,「。最令我困惑的是,\ u00fc是「ü」的正確的Unicode代碼點。我嘗試了很多東西,包括單獨打印每一個unichar,但結果不會改變。無論我在訪問NSDictionary中的值時做什麼似乎都會殺死Unicode字符。我能做些什麼來簡單地獲取地址?

非常感謝您提前!

回答

3

您的代碼或輸出沒有任何問題。您顯示錯誤。以UTF-8編碼的字母'ü'是0xC3 0xBC。在MacRoman字符集中,字節0xC3表示字符'√',字節0xBC表示'º'。看看你的輸出爲UTF-8(它是),而不是MacRoman(它不是),你被設置。

+0

謝謝。我沒有想到這一點,因爲Xcode的調試窗口顯示來自模擬器的字符串很好,我轉發地址的地理編碼器也失敗了。但重啓設備後,地理編碼器運行良好,因此它真的只是一個顯示問題! – aus 2012-04-02 16:56:46

0

使用NSUTF8StringEncoding使用方法編碼字符串:stringWithUTF8String:

例如,

NSString *str = [NSString stringWithUTF8String:"your string for encoding"]; 

至於你的情況

NSString *object = [NSString stringWithUTF8String:[[addressData objectForKey:key] cStringUsingEncoding:NSUTF8StringEncoding]]; 

或者

NSString *object = [NSString stringWithUTF8String:[[addressData objectForKey:key] UTF8String]]; 

讓我知道如果你需要更多的幫助。

希望這會有所幫助。

+0

這應該如何幫助?你將一個字符串轉換爲一個UTF-8字符數組並返回一個字符串,這根本不會改變任何東西。 – Sven 2012-04-01 15:19:07

+0

@Sven:你可以參考http://stackoverflow.com/questions/5447413/nsstring-unicode-encoding-problem – 2012-04-01 15:21:28

+0

謝謝你的回答!但事實證明這確實只是一個顯示問題。 – aus 2012-04-02 16:58:25