2013-02-21 96 views
3

在下面寫的NSData是代碼:無法文件夾

NSData * imageData = [NSData dataWithContentsOfURL:imageURL];     

[imageData writeToFile:savedImagePath options:NSDataWritingAtomic error:&error]; 
          if(error != nil) 
NSLog(@"write error %@", error); 

錯誤:

write error Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0x8b7b850 {NSUnderlyingError=0x8b7d7c0 "The operation couldn’t be completed. No such file or directory", NSFilePath=/Users/alfa-1/Library/Application Support/iPhone Simulator/6.0/Applications/C24B228A-599E-4249-97A7-17775E8A546B/Library/Caches/ChannelListImages/http:/direct.domain.com/files/icons/1-all-cb.jpg, NSUserStringVariant=Folder} 
+0

也許你需要創建中間文件夾... – apascual 2013-02-21 12:43:24

+0

顯示的NSLog你savedImagePath。路徑可能無效 – 2013-02-21 12:44:10

+0

什麼是中間文件夾?如果路徑是/ folderA/folderB/folderC,則爲 – 2013-02-21 12:44:15

回答

1

試試這個樣品。這個對我有用。

聲明 - (的NSString *)datafilepath在.h文件中

-(NSString *) datafilepath{ 
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documents=[path objectAtIndex:0]; 
return [documents stringByAppendingFormat:@"/sample.plist"]; 
} 

任何地方ü要執行寫入功能

NSData * imageData = [NSData dataWithContentsOfURL:imageURL];     
[imageData writeToFile:[self datafilepath]atomically:YES]; 
if(error != nil) 
NSLog(@"write error %@", error); 

希望這有助於!

+0

它應該是[文檔stringByAppendingPathComponent:@「sample.plist」]; – loretoparisi 2013-10-12 21:17:35

5

將數據寫入文件之前。您需要創建文件夾。請按照下列步驟

#define APPLICATION_DATA_DIRECTORY @"Application Data" 
+ (NSString *)cachesDirectoryPath 
// Returns the path to the caches directory. This is a class method because it's 
// used by +applicationStartup. 
{ 
    NSString *  result; 
    NSArray *  paths; 

    result = nil; 
    paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    if ((paths != nil) && ([paths count] != 0)) { 
     assert([[paths objectAtIndex:0] isKindOfClass:[NSString class]]); 
     result = [paths objectAtIndex:0]; 
    } 
    result = [result stringByAppendingPathComponent:APPLICATION_DATA_DIRECTORY]; 
    if (![[NSFileManager defaultManager] fileExistsAtPath:result]) { 
     [[NSFileManager defaultManager] createDirectoryAtPath:result withIntermediateDirectories:YES attributes:nil error:NULL]; 
    } 

    return result; 
} 
在此之後

#define kPhotosDirectoryName @"ApplicationDocuments"

NSMutableString *savePath = [NSMutableString string]; 
    [savePath appendFormat:@"%@/%@",[YOURClass cachesDirectoryPath],kPhotosDirectoryName]; 

    [savePath appendFormat:@"/%@",YOUR_FILE_NAME]; 

    if (![[NSFileManager defaultManager] fileExistsAtPath:savePath]) { 
     //write the data to file here 
    }