Search code examples
objective-ccocoansnotifications

NSFileHandle readInBackgroundAndNotify does not work


Hi I'm using NSFileHandle's readInBackgroundAndNotify method to get notifications when a log file has been updated.

I have the following code:

- (void)startReading
{
    NSString *logPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Logs/MyTestApp.log"];
    NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:logPath];
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self
                           selector:@selector(getData:)
                               name:NSFileHandleReadCompletionNotification
                             object:fh];
    [fh readInBackgroundAndNotify];
}

- (void) getData: (NSNotification *)aNotification
{
     NSLog(@"notification received");
}

However the selector is never called and the notification is not received.


Solution

    1. Add an NSLog to startReading to make sure that's getting called.
    2. Log fh. My guess is that it's nil (most probably because you haven't created MyTestApp.log yet).