Question

I'm experiencing an access problem in my Cordova plugin: my NSFileHandle "loses" context between Cordova calls, and I end up with either an EXC_BAD_ACCESS, a SIGABRT or an Unrecognized Selector sent to instance error. Debugging and digging inside Obj-C's documentation has given me no lead on this, so I'd appreciate your help here very much!

Here's my code. First - the interface:

@interface MyPlugin : CDVPlugin
...
- (void) startWriting:(CDVInvokedUrlCommand*)command;
- (void) stopWriting:(CDVInvokedUrlCommand*)command;
@end  

And the implementation:

....
static NSFileHandle *logFile;


@implementation MyPlugin

- (void) startWriting:(CDVInvokedUrlCommand*)command{
    logFile = [NSFileHandle fileHandleForWritingAtPath:@"path_to_my_file"];
    NSData nsData = [@"Hello World!" dataUsingEncoding:NSUTF8StringEncoding];
    [logFile writeData:nsData];
}

- (void) stopWriting:(CDVInvokedUrlCommand*)command{
    NSData nsData = [@"Goodbye World!" dataUsingEncoding:NSUTF8StringEncoding];
   [logFile writeData:nsData];   
}  

I call startWriting and then stopWriting using cordova.exec. The error occurs on the last line of stopWriting. There were a few times that the problem miraculously disappeared, but in most cases I get one of the aforementioned errors.
It appears that my logFile object closes the file seamlessly, but according to iOS documentation, this usually happens when the NSFileHandle object is deallocated, whereas my object is declared as static, and is not supposed to be deallocated as long as my plugin lives (plus, I see in the XCode debugger that it is still allocated).

What, in your opinion, causes my NSFileHandle object to "lose" the actual file?

Was it helpful?

Solution

Imho - logFile is released once function finishes its job. You should change your code to something like

if (logFile==nil) logFile = [NSFileHandle fileHandleForWritingAtPath:@"path_to_my_file"];

or manually retain/release the logFile object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top