I have tried going through this Question: How Does A Delegate Work and I still don’t seem to have a full grasp on it. I am trying to use the CocoaAsyncSocket library to create a TCP socket connection. Thanks to help from a very friendly SO user, I have the following code to perform a read data request to the server:
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length])];
NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
if(msg)
{
NSLog(@"RX:%@",msg);
}
}
Now, forgive my ignorance as I’m pretty new to iOS development. So now I have this method that I want to invoke which will perform my ReadData. The problem is, I do not know WHERE to put this method (I have several views, with several header/implementation files). I want this method to be a delegate method, but I do not know how to make it a delegate method. I want to invoke this delegate method from my view.
If anyone could explain:
- Where do I put this code? (What file, etc)
- How do I make this a delegate method?
- How do I invoke this delegate method?
I’ve been stuck on this all day, and I’m about to throw it the towel lol. Any and all help is much appreciated. Thanks so much!
EDIT:
This is kind of a bridge from a previous question, but I don’t think that question has too much relevance to this question. Question
Thanks for updating. It is now clearer.
Here are some answers. If it is not clear, please let me know.
– Where do I put this code? (What file, etc)
This is a delegate method of
CocoaAsyncSocket. Back to your first question, when you initialized it, you set yourself (your appDelegate) as the delegate.That means, you will be called from another class. So that means this method should be in the same class where you initialized the object (here
socket) and set it as the delegate. So it stays in appDelegate– How do I make this a delegate method?
You don’t. This is a delegate method itself.
– How do I invoke this delegate method?
You don’t. Another class (here
AsyncSocket) will invoke it.You may now ask, how you pass the data to your
viewControllers?That depends on your design. Once this method is called and you get notified that there is a connection, and data is being read, depending on your design, you pass the data to other view controllers. One way is by using
NSNotification. e.g.