为协议添加参数(委托)

时间:2014-02-27 12:07:32

标签: ios objective-c delegates nsxmlparser nsxmlparserdelegate

我想为委托方法添加一个参数(来自NSXMLParser委托)

这是到目前为止的方法:

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    // save the characters for the current item...
    if ([string   isEqual: @"off"]) {
         myObject.isON = NO; //doesn't know what is myObject
    }

我想要的是什么:

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string:(MyObject*)anObject{
    // save the characters for the current item...
    if ([string   isEqual: @"off"]) {
         anObject.isON = NO;
    }

谢谢

1 个答案:

答案 0 :(得分:1)

首先,您需要将NSXMLParser子类化,添加新的delegate属性,将其称为subclassDelegate或类似的东西,这样您就可以区分超类的委托。在init中是您的超类self.delegate = self;

的代表

响应委托方法并将您不想覆盖的方法转发给self.subclassDelegate响应您要覆盖的方法并在子类协议中覆盖它。

以下是示例:

    @protocol  MyXMLParserDelegate;
@interface MyXMLParser : NSXMLParser<NSXMLParserDelegate>
@property (weak) id<MyXMLParserDelegate> subclassDelegate;
@end

@protocol  MyXMLParserDelegate <NSObject>
- (void)parserDidStartDocument:(NSXMLParser *)parser;
// this is the method that you override
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string withObject:(id)object;
@end

然后在.m

@implementation MyXMLParser

- (id)init
{
    self = [super init];
    if(self) {
        self.delegate = self;
    }
    return self;
}


#pragma mark - repspond to NSXMLParser delegate

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    [self.subclassDelegate parser:parser foundCharacters:string withObject:yourObject];
}