0

I use this code, but "it works" doesn't happen.

DetailViewController.h

[#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@protocol ProtocolNameDelegate

-(void)DoSomething;

@end

@interface DetailViewController : UIViewController {
     id<ProtocolNameDelegate> _delegate;
}

@property (strong, nonatomic) id<ProtocolNameDelegate> _delegate;

DetailViewController.m

@synthesize _delegate;

- (void)viewDidLoad
{
    [super viewDidLoad];

    [_delegate DoSomething];
}

MasterViewController.h

@interface MasterViewController : UITableViewController <ProtocolNameDelegate> 

MasterViewController.m

-(void)DoSomething
{
    NSLog(@"It works");

}

I think i have to add something like:

MasterViewController* mvc = [[MasterViewController alloc] init];
    mvc._delegate = self;

But it gives an error, and by the way will it create another instance of MasterViewController?

Horhe Garcia
  • 882
  • 1
  • 13
  • 28

2 Answers2

1

Instead of

MasterViewController* mvc = [[MasterViewController alloc] init];
mvc._delegate = self;

write this,

DetailViewController* svc = [[DetailViewController alloc] init];
dvc._delegate = self;

You made mistake in implementation.

Abstract of implementation should be.

  • Create Protocol in DetailVC.
  • Create Property for Delegate, Synthesize, and make call.
  • Import DetailVC in MasterVC and include delegate in MasterVC.h
  • Implement protocol method in MasterVC.m
  • Create instance of DetailVC and assign DetailVCObj.delegate = self;
βhargavḯ
  • 9,786
  • 1
  • 37
  • 59
0

In MasterViewController.m, you need to allocate and intialise DetailViewController somewhere

DetailViewController* dvc = [[DetailViewControlleralloc] init];
    dvc._delegate = self;

Also, because you have written [_delegate doSomething] in

DetailviewController's viewDidLoad method,

it means you must set dvc._delegate = self; in MasterViewController.m

before loading dvc's view (before addSubview or anything that loads view).

Puneet Sharma
  • 9,369
  • 1
  • 27
  • 33
  • this made my code ok: SecondViewController *secondVC = (SecondViewController *) segue.destinationViewController; [secondVC setDelegate:self]; – Horhe Garcia Jul 23 '13 at 13:17