2012-08-11 46 views
1

我複製的plist文件來讀取目錄時didFinishLaunchingWithOptions在AppDelegate中是這樣的:複製的plist到文檔目錄,並從中

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
[self performSelector:@selector(copyPlist)]; 
return YES; 
} 

- (void)copyPlist { 
    NSFileManager *fileManger=[NSFileManager defaultManager]; 
    NSError *error; 
    NSArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); 

    NSString *doumentDirectoryPath=[pathsArray objectAtIndex:0]; 

    NSString *destinationPath= [doumentDirectoryPath stringByAppendingPathComponent:@"Obj.plist"]; 

    if ([fileManger fileExistsAtPath:destinationPath]){ 
     NSLog(@"database localtion %@",destinationPath); 
     return; 
    } 
    NSString *sourcePath=[[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"Obj.plist"]; 

    [fileManger copyItemAtPath:sourcePath toPath:destinationPath error:&error]; 
} 

然後我想顯示的plist在我的意見內容像這樣:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Obj.plist"]; 
NSLog(@"plist path %@", path); 

sortedObj = [[NSMutableArray alloc]initWithContentsOfFile:path]; 
NSLog(@"objects %@", sortedObj); 

日誌結果:

數據庫當前位置:

/Users/kdb/Library/Application Support/iPhone Simulator/5.1/Applications/4E165740-01CD-4ED3-8971-FDCCB1751DD1/Documents/Obj.plist 

的plist路徑:

相同數據庫位置

對象:

(空)

內容是空的。 如何使它工作?

plist是一個有字典的數組。

+0

.plist文件的結構怎麼樣?可能是頂級對象不是NSArray(),而是NSDictionary()。你也可以在你的問題中包括你的plist的前幾行嗎? – gschandler 2012-08-11 18:33:48

+0

plist是一個包含字典的數組,例如:array,dict,key,string,key,string,/ dict,dict,key,string,key,string,/ dict,/ array – ingenspor 2012-08-11 18:38:26

+0

你是否在刪除內容?你可以在模擬器中檢查嗎? – 2012-08-11 18:45:27

回答

0

你有沒有試過NSLog資源束中的路徑?它看起來正確嗎?除此之外,我認爲你應該使用此另一種方法找到它:

- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension 

所以,你的方法調用是:

NSString *sourcePAth = [[NSBundle mainBundle] pathForResource:@"Obj" ofType:@"plist"]; 

然後,我不認爲你可以做[[NSMutableArray alloc] initWithContentsOfFile:path];。 相反,嘗試使用的NSDictionary:

NSDictionary *loadedPlist = [[NSDictionary alloc] initWithContentsOfFile:pathString]; 
//and then, if you need to edit it: 
NSMutableDictionary *workingCopy = [loadedPlist mutableCopy]; 

剛剛看了你編輯的問題。 plists不能被視爲數組,它們總是字典,因此必須使用NSDictionary進行反序列化。

我不知道爲什麼它只在沒有日誌的情況下才能正常工作。你可以發佈他們嗎?此外,即使它似乎使用NSMutableArray工作,如果您遵守NSDisctionary反序列化風格,調試問題將更容易。

+0

感謝您提供這些建議,我將記錄我的代碼並更新問題 – ingenspor 2012-08-11 19:01:53

+0

更新日誌結果。 – ingenspor 2012-08-11 21:15:01

+0

事情是:我使用MutableArray sortedObj和NSSortDescriptor來填充字典的TableView單元格,並且當我從包中訪問plist時,此工作正常。現在對象返回null。 – ingenspor 2012-08-11 22:53:31

相關問題