代码之家  ›  专栏  ›  技术社区  ›  Corey Floyd

将数据保存到缓存目录时出错(iPhone)

  •  17
  • Corey Floyd  · 技术社区  · 17 年前

    - (void)writeData{
    
        if(cacheFileName==nil)
            return;
        if(cacheDirectoryPath==nil)
            return;
    
    
        if (![[NSFileManager defaultManager] fileExistsAtPath:[self filePath]]) {        
    
            NSData *imageData = UIImageJPEGRepresentation(self.image, 0.9);
    
            NSError *writeError= nil;
    
            BOOL didWrite =  [imageData writeToFile:[self filePath] options:NSAtomicWrite error:&writeError];
    
            if(writeError)
                NSLog([writeError localizedDescription]);
    
            if(didWrite)
                NSLog(@"image saved");
            else
                NSLog(@"image not saved");
    
    
        }
    }
    
    
    
    
    
     - (NSString *)filePath{
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
        NSString *cacheDirectory = [paths objectAtIndex:0]; 
        NSString *filename = [cacheDirectory stringByAppendingPathComponent:cacheDirectoryPath]; 
        filename = [filename stringByAppendingPathComponent:cacheFileName]; 
        NSLog(filename);
    
        return filename;
    
    }
    

    2009-06-23 16:39:19.740 XXX[33454:20b] Operation could not be completed. (Cocoa error 4.)
    

     NSFileNoSuchFileError = 4,                 // Attempt to do a file system operation on a non-existent file
    

    这没有意义,因为文件不应该存在。

    - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
    

    1 回复  |  直到 17 年前
        1
  •  28
  •   Brad The App Guy    13 年前

    -[NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error:]