【问题标题】:Where does [NSData writeToFile] write to?[NSData writeToFile] 写入哪里?
【发布时间】:2012-10-11 01:22:18
【问题描述】:

我写了一个简单的程序来帮助我调试。

#import "UIImage+saveScreenShotOnDisk.h"

@implementation UIImage (saveScreenShotOnDisk)

-(void)saveScreenshot{
    NSData * data = UIImagePNGRepresentation(self);
    [data writeToFile:@"foo.png" atomically:YES];
}

@end

执行后,我想知道foo.png在哪里。

我去了

~Library/Application Support

我找不到foo.png。它在哪里?

如果我这样做

BOOL result = [data writeToFile:@"foo.png" atomically:YES];

结果将是NO,这有点奇怪,因为模拟器不像 iPhone,可以在任何地方写入。

【问题讨论】:

  • 它在您当前的工作目录 (CWD) 中,通常是您的程序启动的地方。
  • 它不存在,如果我这样做 BOOL result = [data writeToFile:@"foo.png" atomically:YES];结果是 NO。
  • 我想知道 foo.png 到底在哪里。和我的感觉一样! @Paul Brewczynski 在下面提供了答案(尽管是在事实发生两年后)。在 Xcode6.2 中,在 Cocoa Project Navigator 中,如果我打开 Products 文件夹并右键单击 MyAppName.app 并选择 Show In Finder,tada!我在 MyAppName.app 旁边看到了我保存的文件。就我而言,我使用了名称@"savedArray",Finder中的文件名是savedArray,如果我打开文件,它是一个plist文件。

标签: ios objective-c nsdata xcode4.5


【解决方案1】:

您需要将 NSData 对象指向您希望保存数据的路径:

NSString *docsDir;
NSArray *dirPaths;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"foo.png"]];
[data writeToFile:databasePath atomically:YES];

这会将您的文件保存在设备(或模拟器)上的应用文件夹中。

【讨论】:

  • 这就是我最终所做的。我想如果我们不指定路径,它将转到一些“默认”路径。我错了。
【解决方案2】:

存储文件的默认位置是存储可执行文件的文件夹。

通过右键单击 Products->YourExecutable 查看可执行文件的存储位置:

然后在finder中打开。

这里pawel.plist资源创建方式

NSArray *a = @[@"mybike", @"klapki", @"clapki", @"ah"];
[a writeToFile:@"pawel.plist" atomically:NO];

【讨论】:

    【解决方案3】:

    对于 Swift,基于 Shachar 的回答:

    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] + "/foo.png"
    data?.writeToFile(path, atomically: true)
    

    【讨论】:

      【解决方案4】:

      你忘了提供你想写的位置或路径。检查这个 writeToFile:options:error:

      将接收器中的字节写入给定路径指定的文件。

      - (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)mask error:(NSError **)errorPtr
      

      参数

      路径

      The location to which to write the receiver's bytes.
      

      面具

      A mask that specifies options for writing the data. Constant components are described in “NSDataWritingOptions”.
      

      errorPtr

      If there is an error writing out the data, upon return contains an NSError object that describes the problem.
      

      【讨论】:

        【解决方案5】:

        您可以搜索“NSDocumentsDirectory”,我通常使用此方法搜索文档目录的路径,然后附加我的文件名。在方法writeToFile: 中,提供了这个附加路径。然后使用 iTunes>应用程序,滚动到底部,选择您的应用程序,您应该可以看到保存的文件。

        PS:您应该在 plist 中设置一个 valur,指定您的应用程序使用手机存储。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-05-18
          • 2011-09-21
          • 2016-04-18
          • 2011-08-02
          • 2011-11-06
          • 1970-01-01
          • 2015-01-21
          • 1970-01-01
          相关资源
          最近更新 更多