@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发送消息,为什么这不起作用?
答案 0 :(得分:2)
您需要将b设置为委托。
self.delegate = b;
然而,使用代表的通常方式是反过来:
SomeClass* obj = [[SomeClass alloc] init];
obj.delegate = self;
请注意,委派不是Objective-C的功能。这只是一种设计模式! http://en.wikipedia.org/wiki/Delegation_pattern
答案 1 :(得分:1)
如果我理解你正在尝试做什么,这应该是正确的:
-(void)someMethod {
[delegate didSomeAction];
}
-(void)viewDidLoad {
delegate = [[B alloc] init];
}
否则,当您致电[delegate didSomeAction];
时,delegate
为零,且该消息将被忽略。
答案 2 :(得分:0)
对象通常不会自己创建代理。相反,B
应创建A
的实例并将其自身设置为该对象的委托:
@implementation B
- (void)awakeFromNib {
self.a = [[[A alloc] init] autorelease];
self.a.delegate = self;
}
@end
答案 3 :(得分:0)
如果您只想将简单消息发送到其他类,可以使用NSNotification
在B类文件中
- (void)someMethod {
[[NSNotificationCenter defaultCenter] postNotificationName:@"NofifyMe" object:self userInfo:nil];
}
在课程文件中
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSomeAction:) name:@"NofifyMe" object:nil];
- (void)didSomeAction {
}
因此,只要你的someMethod会调用,那么你的B类只会向你的A类发送一条消息来调用didSomeAction。并在dealloc中删除观察者
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}