开发者

Objective c , delegates

@protocol SomeDelegate
- (void) didSomeAction;
@end

@interface A:ViewController {
id<SomeDelegate> delegate;
}

@property (nonatomic, retain) id<SomeDelegate> delegate;

@implementation A
@synthesize delegate;

- (void)someMethod {
[delegate didSomeAction];
}

- (void)viewDidLoad {
B *b = [[B alloc] init];
}

/*=========================*/

@interface B:NSObject<SomeDelegate> {

}

@implem开发者_运维知识库entation B

#pragma mark - 
#pragma mark SomeDelegate methods

- (void)didSomeAction {

}

B should send message to A, why this is not working?


You need to set b as delegate.

self.delegate = b;

However the usual way to use delegates is the other way round:

SomeClass* obj = [[SomeClass alloc] init];
obj.delegate = self;

Note that Delegation is not a feature of Objective-C. It is only a design pattern! http://en.wikipedia.org/wiki/Delegation_pattern


If I understand correctly what you are trying to do, this should be correct:

 -(void)someMethod {
    [delegate didSomeAction];
 }

 -(void)viewDidLoad {
    delegate = [[B alloc] init];
 }

otherwise, when you call [delegate didSomeAction];, delegate is nil and the message is ignored.


Objects don’t usually create their delegates themselves. Instead B should create an instance of A and set itself as the delegate of that object:

@implementation B

- (void)awakeFromNib {
    self.a = [[[A alloc] init] autorelease];
    self.a.delegate = self;
}

@end


If you just want to send the simple message to other class, can use NSNotification

In B class file

- (void)someMethod {
     [[NSNotificationCenter defaultCenter] postNotificationName:@"NofifyMe" object:self userInfo:nil];
}

In A class file

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSomeAction:) name:@"NofifyMe" object:nil];
- (void)didSomeAction {

}

So whenever your someMethod will call, then your B class will just send a message to your class A to invoke didSomeAction. and in dealloc remove the observer

-(void)dealloc{
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [super dealloc];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜