S.J
S.J

Reputation: 3071

What I am doing wrong with Obj-c delegate

I created a new tabbed view project in Xcode in firstViewController I created a protocol like this

@protocol myProtocol <NSObject>
-(void)myProtocolMethodOne;
@end


@interface FirstViewController : UIViewController

@property (weak) id<myProtocol> mypDelegate;

- (IBAction)button1Tap:(id)sender;

@end

In .m file I did this

@synthesize mypDelegate;
.
.
.
- (IBAction)button1Tap:(id)sender
{
    [mypDelegate myProtocolMethodOne];
}

This is secondViewController .h file

@interface SecondViewController : UIViewController <myProtocol>

@property (strong) FirstViewController *fvc;

@end

This is .m file

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Second", @"Second");
        self.tabBarItem.image = [UIImage imageNamed:@"second"];
        _fvc = [[FirstViewController alloc]init];
        [_fvc setMypDelegate:self];
    }
    return self;
}


-(void)myProtocolMethodOne
{
    NSLog(@"2nd VC");
    [[self tabBarItem]setBadgeValue:@"ok"];
}

myProtocolMethodOne is not working, what I did wrong?

Upvotes: 0

Views: 99

Answers (2)

iPatel
iPatel

Reputation: 47099

Here is Best site with source code for learn basic about protocol.

////// .h file

#import <Foundation/Foundation.h>

@protocol myProtocol <NSObject>

@required

-(void)myProtocolMethodOne;

@end

@interface FirstViewController : UIViewController
{
    id <myProtocol> mypDelegate;
}

@property (retain) id mypDelegate;

- (IBAction)button1Tap:(id)sender;

@end

///////// .m file

@synthesize mypDelegate;
.
.
.
.
- (void)processComplete
{
    [[self mypDelegate] myProtocolMethodOne];
}

Upvotes: 0

Yaman
Yaman

Reputation: 3991

_fvc = [[FirstViewController alloc]init];
[_fvc setMypDelegate:self];

You're setting the delegate to a completely new FirstViewController, but not the one who trigger your method - (IBAction)button1Tap:(id)sender

You have to pass your delegate when you're doing the transition between your 2 view controllers, for example in - prepareForSegue: or when you doing [self.navigationController pushViewController:vc animated:YES]

Upvotes: 2

Related Questions