Skip navigation.
 
mlHelp with notifications and NSFileHandle threads
FROM : Wan, Nathan (CIV)
DATE : Fri Jun 27 22:15:09 2008

Hi all,

I am new to Objective-C and Cocoa, but I am learning it for what I thought was a pretty small project.  I need some help with the notification system and the run loop in Cocoa.  The end result is supposed to be a program that constantly reads and writes data from a serial port to a local file, but baby step here.  It was suggested that I use NSFileHandle class to make my program more thread safe.  This is a quick test I tried to write out.  I would change the data in the text file, and hopefully something will show up on the console:

PS what's a proper way to work between NSData and NSString?

//CODE

#import <Cocoa/Cocoa.h>
#import <Foundation/NSFileHandle.h>
#import <Foundation/NSString.h>
#import <Foundation/NSNotificationCenter.h>
#import <stdio.h>

@interface test : NSObject

-(void) writeDataReadInBackground:(NSNotification *)notification;
-(void) testWriteData:(NSData *)data;

@end


int main(int argc, char *argv[])
{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSData *aData = [@"Test" dataUsingEncoding: NSASCIIStringEncoding];
    NSFileHandle *in = [NSFileHandle fileHandleForReadingAtPath:@"/Users/_me_/test.txt"];
 
    if(in == nil)
        printf("somethig wrong\n");
 
    test *t = [[test alloc] init];
 
    [[NSNotificationCenter defaultCenter] addObserver: t selector:@selector(writeDataReadInBackground:) name: NSFileHandleDataAvailableNotification object: nil];

    [t testWriteData: aData];
 
    [stdIn waitForDataInBackgroundAndNotify];
 
    while(1)
        sleep(5);
 
    [t release];
    [pool release];
 
    return 0;
}


@implementation test
- (void) writeDataReadInBackground:(NSNotification *)notification {
 
    printf("Notification recieved\n");
    }
 
- (void) testWriteData:(NSData *)data {

        NSFileHandle *stdOut = [NSFileHandle fileHandleWithStandardOutput];
     
        [stdOut writeData:data];
     
    }
@end

//END_CODE

Thanks!!

<EOM>

Related mailsAuthorDate
No related mails found.