1

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!

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

If it makes sense to do that, and particularly if it makes sense to name the parameter 'self', then there's a good chance that the function in question should really be a method of whatever class 'self' belongs to.
@Caleb.. good point. I should just make this function belong to the class rather than being tied to a particular instance.
2

You can also make class functions.

@interface MyClass : NSObject
{}
+ (void) myDoSometing;
@end

void myDo(int foo)
{
  [MyClass DoSomething];
}

1 Comment

Upvoted. I think that making this a class function is appropriate. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.