Reputation: 19684
I am new to Objective-C so what I'm trying to do might not be possible. I am refactoring a large C function into multiple C functions and Obj-C methods.
Is this possible?
The following will not build and complains
'self' undeclared.
void serverCB(CFReadStreamRef stream, CFStreamEventType event, void *myPtr)
{
switch(event) {
case kCFStreamEventHasBytesAvailable:
[self readStreamData:stream];
break;
case kCFStreamEventErrorOccurred:
NSLog(@"A Read Stream Error Has Occurred!");
break;
case kCFStreamEventEndEncountered:
NSLog(@"A Read Stream Event End!");
break;
default:
break;
}
}
-(void) readStreamData: (CFReadStreamRef)stream
{
NSData *data = [[NSMutableData alloc] init]; //TODO: I have to flush this at some point..?
uint8_t buffer[1024];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buffer maxLength:1024];
if(len > 0)
{
[data appendBytes:&buffer length:len];
}
NSString *serverText = [[NSString alloc] initWithData: data encoding:NSASCIIStringEncoding];
[data release]; // I got my string so I think I can delete this
[self processServerMessages:serverText];
}
}
In the first function listed, 'serverCB' I am trying to send the 'readStreamData' message to the current object. So can I only call c functions from c functions?
Thanks!
Upvotes: 1
Views: 1514
Reputation: 1826
You can also make class functions.
@interface MyClass : NSObject
{}
+ (void) myDoSometing;
@end
void myDo(int foo)
{
[MyClass DoSomething];
}
Upvotes: 2
Reputation: 523704
You can call Objective-C methods from a C function. But as the error told you, the variable self
is not defined. You need to pass self
as a parameter to serverCB
, e.g.
void serverCB(CFReadStreamRef stream, CFStreamEventType event, void* myPtr, id self) {
...
[self readStreamData:stream];
...
}
...
serverCB(stream, event, NULL, self);
Upvotes: 2