开发者

Simple write to file does not work for me

I cannot get this simple string to write to a file. Please look at my code. This is a simple nib with an NSTextField and a button. The log shows I am getting the string value fine, but it does not write.

//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 s开发者_运维技巧tringValue];
    NSString * path = @"data.txt";
    NSLog(@"test String %@", zStr);
    [zStr writeToFile:path 
           atomically:YES 
             encoding:NSASCIIStringEncoding 
                error:nil]; 

}


@end


You have to provide an entire file path to most likely the Documents directory, not just a file name.

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]; 


You need to provide an absolute path.

This code from another answer gives you the path to the documents directory of your app:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜