2012-11-19 34 views
0

我有幾個問題和一些問題:目標C訪問一個NSBundle

我想要做什麼:

在MyApp.app/Assets/Debug/debug.xml重命名文件到MyApp.app/資產/調試/ debug_2.xml

1. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"debug" ofType:"xml" inDirectory:@"Assets"]; returns (null) 

2. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"debug" ofType:"xml" inDirectory:@"Debug"]; returns (null) 

3. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"debug" ofType:"xml"]; WORKS(it finds the file EVEN if its not in the .app its in .app/Assets/Debug.xml) 

但是:

if ([fm fileExistsAtPath:path]) { 

NSString *newPath = [[NSBundle mainBundle] pathForResource:@"newfile" ofType:@"xml"]; 

      [fm copyItemAtPath:path toPath:newPath error:NULL]; 

     } else { 
      NSLog(@"File does not exists"); 
     } 

代碼總是拋出此錯誤:

-[NSFileManager copyItemAtPath:toPath:error:]: destination path is nil' 

當然該文件不存在,但它不是文件路徑相同的路徑..只是用另一個名字:)

我想在的.app文件夾中的文件重命名具有相同路徑只是另一個名字。

任何幫助表示讚賞!

另外在上面的示例1和2中:如果我使用inDirectory參數,爲什麼它會給我空路徑?我添加了一個文件夾,以構建ressources和這樣的..我測試的所有

感謝

回答

2

您不能修改資源的應用程序包。它基本上是隻讀的。 pathForResource方法只返回現有文件的路徑。

您必須將任何新文件寫入文檔或緩存目錄。你把它們放在哪裏取決於它們是否可以重新生成,以及它們是否應該備份。有關更多信息,請參閱this documentation

+0

或者,如果你不想用的iCloud進行同步其圖書館目錄。 – Dave

0

如果你想在應用程序沙箱來創建目錄:

applicationDataFolder = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]; //OR NSDocumentsDirectory 
    NSString* libraryFolderPath = [[[MAFCore sharedInstance] applicationDataFolder] stringByAppendingPathComponent:@"myFolder"]; 
    BOOL dirExists = [[NSFileManager defaultManager] fileExistsAtPath:libraryFolderPath]; 
    if(dirExists == NO){ 
     [[NSFileManager defaultManager] createDirectoryAtPath:libraryFolderPath withIntermediateDirectories:NO attributes:nil error:nil]; 
    } 
+0

我不想要庫路徑。我想.app /文件夾不是.app/Library/Folder。我知道如何訪問documentsdirectory和所有,但我不知道.app等 – xCoder

0

你需要閱讀使用方法開發者手冊...

我會解釋它給你:

pathForResource:ofType:inDirectory:

If inDirectory is nil, this method searches the top-level nonlocalized resource directory and the top-level of any language-specific directories. [cut] For example, suppose you have a Mac OS X application with a modern bundle and you specify @"Assets" for the subpath parameter. This method would first look in the Contents/Resources/Assets directory of the bundle...

和您的文件不在內容/資源/資產

pathForResource:不適用於不存在的文件。

你需要做什麼:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"debug" ofType:"xml"]; 
NSString *newPath = [filePath stringByDeletingLastPathComponent]; 
newPath = [newPath stringByAppendingPathComponent:@"debug_2.xml"];