2009-07-02 103 views
26

所以我有一個plist結構化字符串,它動態獲取(而不是從文件系統)。我將如何將此字符串轉換爲NSDictionary。解析Plist(NSString)到NSDictionary

我試圖將其轉換NSData的,然後用一個NSPropertyListSerialization NSDictionary的,但它返回「[NSCFString objectAtIndex:]:無法識別的選擇發送到實例0x100539f40」當我試圖訪問NSDictionary中,顯示出我的解釋是不是成功創建。 NSString的(即plist中的數據)的

實施例:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
<dict> 
<key>Key1</key> 
<dict> 
    <key>Test1</key> 
    <false/> 
    <key>Key2</key> 
    <string>Value2</string> 
    <key>Key3</key> 
    <string>value3</string> 
</dict> 
</dict> 
</plist> 

謝謝!

回答

72

Serializing a Property List

NSData* plistData = [source dataUsingEncoding:NSUTF8StringEncoding]; 
NSString *error; 
NSPropertyListFormat format; 
NSDictionary* plist = [NSPropertyListSerialization propertyListWithData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error]; 
NSLog(@"plist is %@", plist); 
if(!plist){ 
    NSLog(@"Error: %@",error); 
    [error release]; 
} 
12

試試這個:

NSData * data = [yourString dataUsingEncoding:NSUTF8StringEncoding]; 

NSString *errorDesc = nil; 
NSPropertyListFormat format; 
NSDictionary * dict = (NSDictionary*)[NSPropertyListSerialization 
             propertyListFromData:data 
             mutabilityOption:NSPropertyListMutableContainersAndLeaves 
             format:&format 
             errorDescription:&errorDesc]; 
+0

完美!謝謝! – christo16 2009-07-02 03:43:38

+0

除了內存泄漏,但它發生(: – Jacob 2009-09-24 09:45:32

1

I've tried converting it NSData and then to a NSDictionary with NSPropertyListSerialization, but it returns "[NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x100539f40" when I attempt to access the NSDictionary, showing that my Dictionary was not successfully created.

沒有,它沒有顯示出這樣的事情。它顯示的是你試圖將一個字符串視爲一個數組。您需要確定plist中的哪個位置要獲取數組,以及爲什麼會出現一個字符串,您希望獲得一個數組 - 例如,是否錯誤地創建了plist(字符串放入其中,一個數組)或正在檢查它不正確(字符串的存在是正確的;隨後期望數組是錯誤的)。