【问题标题】: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

【问题讨论】:

    标签: objective-c cocoa file-io nsstring


    【解决方案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"];
      

      【讨论】:

        猜你喜欢
        • 2016-02-10
        • 1970-01-01
        • 2018-12-04
        • 2014-08-02
        • 2016-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多