简单的写入文件对我不起作用

Posted

技术标签:

【中文标题】简单的写入文件对我不起作用【英文标题】:Simple write to file does not work for me 【发布时间】:2011-09-26 23:39:59 【问题描述】:

我无法将这个简单的字符串写入文件。 请看我的代码。这是一个带有NSTextField 和按钮的简单笔尖。日志显示我得到的字符串值很好,但它没有写入。

//Quick.h

#import <Foundation/Foundation.h>

@interface Quick : NSObject

    IBOutlet NSTextField * aString;


-(IBAction)wButton:(id)sender;

@end

//Quick.m

#import "Quick.h"

@implementation Quick

- (id)init

    self = [super init];
    if (self) 
        // Initialization code here.
    

    return self;


-(IBAction)wButton:(id)sender

    NSString * zStr = [aString stringValue];
    NSString * path = @"data.txt";
    NSLog(@"test String %@", zStr);
    [zStr writeToFile:path 
           atomically:YES 
             encoding:NSASCIIStringEncoding 
                error:nil]; 




@end

【问题讨论】:

【参考方案1】:

您必须提供最有可能是 Documents 目录的完整文件路径,而不仅仅是文件名。

NSString *zStr = [aString stringValue];
NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *directory = [paths objectAtIndex:0];
NSString *fileName = @"data.txt";
NSString *filePath = [directory stringByAppendingPathComponent:fileName];
[zStr writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:nil]; 

【讨论】:

【参考方案2】:

您需要提供绝对路径。

another answer 中的这段代码为您提供了应用程序文档目录的路径:

 [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

【讨论】:

以上是关于简单的写入文件对我不起作用的主要内容,如果未能解决你的问题,请参考以下文章

简单的 Spring @CreatedDate 注释对我不起作用

AsyncSocket 对我不起作用

beginSheet 方法对我不起作用

WordPress - CSS 导入对我不起作用

为啥 webpack 代码拆分对我不起作用?

Tailwind css 背景图片对我不起作用