How to set a delegate in a different class

2019-04-07 13:56发布

问题:

I'm working with NSXMLParser that parses a xml document. You have to set the delegate which we would be called every time the parser finds an element. The examples I've looked at all set the delegate to be the same class that's createing:

NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:filename];
[parser setDelegate: self];

Other examples set the delegate to be the parent. What if I want another class (not related to the same class) to handle the delegate. What is the syntax to do so?

I've done this but it doesn't work.

@interface Util : NSObject <NSXMLParserDelegate> {
    //Some code here
}

//functions for the delegate and the implementation on the Util.m
//.
//.
//.

Thx for your answers.

I forgot to say that when calling the delegate I assumed that it would be something like this:

[parser setDelegate:Util];

I assumed this knowing that to set the delegate for the same class the message is:

[parser setDelegate:self];

回答1:

You have to create the Util object first.

The delegate has to be an actual instance of a class :)

Util* util = [[Util alloc] init];
[parser setDelegate:util];
[util release];