0

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 stringValue];
    NSString * path = @"data.txt";
    NSLog(@"test String %@", zStr);
    [zStr writeToFile:path 
           atomically:YES 
             encoding:NSASCIIStringEncoding 
                error:nil]; 

}


@end
jscs
  • 63,694
  • 13
  • 151
  • 195
Miek
  • 1,127
  • 4
  • 20
  • 35

2 Answers2

3

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]; 
zaph
  • 111,848
  • 21
  • 189
  • 228
2

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"];
Community
  • 1
  • 1
James Webster
  • 31,873
  • 11
  • 70
  • 114