2013-08-05 156 views
3

我想製作多個目錄,但我不知道如何。這是我的代碼,直到現在。在iOS的文檔文件夾中創建多個目錄

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder 
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"tops",@"bottoms",@"right" ]; 

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) 
     [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder 

} 

我想有4個目錄,命名爲頂部底部右側和左側但是如果我做它用上述方法不工作..有沒有辦法使用這個代碼,以使多個目錄?或者是我的代碼錯了?謝謝!

+0

需要迭代四次創造4個目錄 –

+0

嗯.. [這個確切的問題( http://stackoverflow.com/questions/18055646/creating-multiple-directory-in-documents)前一段時間被另一個用戶問過(被低估並將**擱置**)。而你的個人資料是在幾分鐘前創建的!我很懷疑。 – Amar

+0

@Amar你說得對。它看起來像是一樣的。 –

回答

8

試試看看這個代碼。

按照您的要求創建目錄。

NSArray *directoryNames = [NSArray arrayWithObjects:@"tops",@"bottoms",@"right",@"left",nil]; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder 

for (int i = 0; i < [directoryNames count] ; i++) { 
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]]; 
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) 
     [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder 
} 

要在您的應用程序的任何位置使用您創建的目錄。

NSArray *directoryNames = [NSArray arrayWithObjects:@"tops",@"bottoms",@"right",@"left",nil]; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder 

// This will return the folder name in the 0 position. In yours "tops" 
NSString *topDirPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:0]]; 
// This will return the file path in your "tops" folder 
NSString *filePath = [topDirPath stringByAppendingPathComponent:@"MYIMAGE"]; 

要保存圖像文件

NSData *imageDataToStore = UIImagePNGRepresentation(image); 
[imageDataToStore writeToFile:filePath atomically:YES]; 

若要檢索圖像文件

// Convert the file into data and then into image. 
NSData *imageData = [[NSData alloc] initWithContentsOfFile:filePath]; 
UIImage *yourImage = [UIImage imageWithData:imageData]; 
+0

我得到的錯誤說使用未聲明的標識符「我」,我應該如何回憶該目錄,以便我可以保存圖片.. – AppleDevram

+0

對不起,我已經寫在SO代碼框中的代碼。只有這樣。現在我已經在'for'循環中聲明瞭'i'。現在檢查。 –

+0

最後還有一個問題,您如何回憶目錄,以便我可以將照片保存在我創建的目錄中。 – AppleDevram

相關問題