【问题标题】:Setup and send custom delegate method within init?在 init 中设置和发送自定义委托方法?
【发布时间】:2012-07-12 03:01:36
【问题描述】:

我有一个关于初始化自定义委托的问题。 在 MyScrollView initWithFrame 方法中,我需要发送我的委托的第一个位置。但是那里仍然未知,因为我在初始化程序之后在 MyCustomView 中设置了委托。

我该如何解决这个问题,所以即使在 init 中也会调用委托? 谢谢你的帮助。。

MyCustomView.m

 self.photoView = [[MyScrollView alloc] initWithFrame:frame withDictionary:mediaContentDict];
 self.photoView.delegate = self;
//....

MyScrollView.h
@protocol MyScrollViewDelegate
-(void) methodName:(NSString*)text;
@end
@interface MyScrollView : UIView{
 //...
    __unsafe_unretained id <MyScrollViewDelegate> delegate;
}
@property(unsafe_unretained) id <MyScrollViewDelegate> delegate;


MyScrollView.m

-(id) initWithFrame:(CGRect)frame withDictionary:(NSDictionary*)dictionary{ 
self.content = [[Content alloc] initWithDictionary:dictionary];

    self = [super initWithFrame:frame];
    if (self) {
      //.... other stuff

     // currently don´t get called
     [self.delegate methodName:@"Test delegate"];
}
return self;
}

【问题讨论】:

    标签: objective-c ios delegates initialization


    【解决方案1】:

    我确定你已经定义了:

    - (id)initWithFrame:(CGRect)frame withDictionary:(NSDictionary *)dictionary;

    然后,也传递委托:

    - (id)initWithFrame:(CGRect)frame withDictionary:(NSDictionary *)dictionary withDelegate:(id&lt;MyScrollViewDelegate&gt;)del;

    在实施文件中:

    - (id)initWithFrame:(CGRect)frame withDictionary:(NSDictionary *)dictionary withDelegate:(id<MyScrollViewDelegate>)del {
        // your stuff...
    
        self.delegate = del;
        [self.delegate methodName:@"Test delegate"];
    
    }
    

    使用它:

    self.photoView = [[MyScrollView alloc] initWithFrame:frame withDictionary:mediaContentDict withDelegate:self];
    

    【讨论】:

    • and darren:非常感谢您的快速回复。伟大的社区,伙计们。现在它完美无缺。好的!祝你有美好的一天。
    【解决方案2】:

    一种选择可能是在您的自定义类的初始化程序中传递您的委托:

    -(id)initWithFrame:(CGRect)frame withDictionary:(NSDictionary*)dictionary delegate:(id)delegate 
    { 
        self = [super initWithFrame:frame];
        if (self == nil )
        {
            return nil;
        }
        self.content = [[Content alloc] initWithDictionary:dictionary];
        self.delegate = delegate;
        //.... other stuff
    
        // Delegate would exist now
        [self.delegate methodName:@"Test delegate"];
    
        return self;
    }
    

    【讨论】:

    • 与我的回答类似,只需注意将方法签名中的 delegate 变量名称更改为 delegate 以外的名称,因为使用了该名称。
    猜你喜欢
    • 2021-08-29
    • 2018-11-13
    • 1970-01-01
    • 2011-07-01
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    相关资源
    最近更新 更多