Crystal
Crystal

Reputation: 29468

Cannot create a file using stringByAppendingPathComponent

This code has worked up until yesterday in my app:

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *applicationDocDirectory = [paths objectAtIndex:0];
        NSLog(@"%@", applicationDocDirectory);
        NSString *tempFilePath = [applicationDocDirectory stringByAppendingPathComponent:@"temp.txt"];  

    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL success = [fileManager fileExistsAtPath:tempFilePath];

I continue to get Cocoa error code 4, that my file doesn't exist at the path. I checked the path and the path is correct. Is there any obvious reason why this code stopped working? I tried cleaning, deleting my app from the simulator or the device and that fixed it for awhile, but then it just stopped working. Not really sure what else is going in that could be causing this issue. THanks.

Upvotes: 0

Views: 183

Answers (1)

Mark
Mark

Reputation: 6128

You can't create a file by using -stringByAppendingPathComponent. That creates an autoreleased NSString object.

If this has been working then the "temp.txt" must already exist.

To create the file you can use:

- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)contents attributes:(NSDictionary *)attributes

To create a file from an NSString you can use:

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error

Upvotes: 1

Related Questions