目标c,代表
@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> {
}
@implementation B
#pragma mark -
#pragma mark SomeDelegate methods
- (void)didSomeAction {
}
B 应该向 A 发送消息,为什么这不起作用?
@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> {
}
@implementation B
#pragma mark -
#pragma mark SomeDelegate methods
- (void)didSomeAction {
}
B should send message to A, why this is not working?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要将 b 设置为委托。
然而,使用委托的通常方法是相反的:
请注意,委托不是 Objective-C 的一个功能。这只是一种设计模式!
http://en.wikipedia.org/wiki/Delegation_pattern
You need to set b as delegate.
However the usual way to use delegates is the other way round:
Note that Delegation is not a feature of Objective-C. It is only a design pattern!
http://en.wikipedia.org/wiki/Delegation_pattern
如果我正确理解你想要做什么,这应该是正确的:
否则,当你调用
[delegate didSomeAction];
时,delegate
为零并且消息被忽略。If I understand correctly what you are trying to do, this should be correct:
otherwise, when you call
[delegate didSomeAction];
,delegate
is nil and the message is ignored.对象通常不会自己创建它们的委托。相反,
B
应该创建A
的实例并将其自身设置为该对象的委托:Objects don’t usually create their delegates themselves. Instead
B
should create an instance ofA
and set itself as the delegate of that object:如果您只想向其他类发送简单消息,可以
在 B 类文件中
使用 NSNotification 在A 类文件中
因此,每当您的 someMethod 调用时,您的 B 类都会向您的 A 类发送一条消息以调用 didSomeAction。并在 dealloc 中删除观察者
If you just want to send the simple message to other class, can use NSNotification
In B class file
In A class file
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