ios - 向协议(protocol)添加参数(委托(delegate))

标签 ios objective-c delegates nsxmlparser nsxmlparserdelegate

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

这是目前的方法:

- (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;
    }

谢谢

最佳答案

首先你需要继承你的 NSXMLParser,添加新的 delegate 属性,调用它 subclassDelegate 或类似的东西,这样你就可以区分 super 类的委托(delegate)。在 init 中是你父类(super class)的委托(delegate) self.delegate = self;

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

例子如下:

    @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];
}

关于ios - 向协议(protocol)添加参数(委托(delegate)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22068070/

相关文章:

iphone - touchesEnded :withEvent: not being called from my UIView, 位于 UITableView 之上

ios - MpMovieplayer加载期间如何显示缓冲符号/符号

iPhone/Cocoa Touch - 将 UITableViewCell 背景从一种颜色更改为另一种颜色

iOS 在键盘之前启动 UIView?

iphone - 将应用程序委托(delegate)定义为常量?

ios - 使单个单元格重叠

ios - MFSideMenu 如何在另一个 ViewController 中加载

ios - 无效上下文 0x0。如果要查看回溯,请设置 CG_CONTEXT_SHOW_BACKTRACE 环境变量。

.net - 不支持 C++/CLI 使用 Action<...,...> 和 Func<...>?

c# - C# 委托(delegate)可以使用对象类型来更通用吗?