koke
koke

Reputation: 69

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> {

}

@implementation B

#pragma mark - 
#pragma mark SomeDelegate methods

- (void)didSomeAction {

}

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

Upvotes: 0

Views: 131

Answers (4)

Praveen-K
Praveen-K

Reputation: 3401

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

Upvotes: 0

gcbrueckmann
gcbrueckmann

Reputation: 2453

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

Upvotes: 0

Felix
Felix

Reputation: 35384

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

Upvotes: 2

sergio
sergio

Reputation: 69027

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.

Upvotes: 1

Related Questions