Harish
Harish

Reputation: 1519

custom delegate being null iOS

I know this should be a simple thing to fix, but I can't see what's going wrong. May be extra pair will help. Here is what I am trying to do.

  1. In my table view controller, there is an (+) button on the navigation controller to add new item.
  2. I have a modal segue that takes it to the next view controller. User fills in a form and hit saves the table view controller reloads with the newly added record.

To do this, I implemented protocol with a delegate.

MyFormViewController.h

protocol MyCustomDelegate <NSObject>

@required

- (void)addNewRecord:(myFormViewController *)formViewController itemToAdd:(Item *)item;

@end

@property (nonatomic,weak) id<MyCustomDelegate> delegate;

MyFormViewController.m

@synthesize delegate;

- (IBAction)addItem:(id)sender {
    Item *item = [[Item alloc]init];

    item.name = itemName.text;
    item.desc = itemDescription.text;

    // I am having problem here, self.delegate is being null even though, it's being set in    prepareForSegue.
    if ([self.delegate respondsToSelector:@selector(addNewRecord:)]) {

        [self.delegate addNewRecord:self itemToAdd:item];
    }
    else{

        // delegate is getting set to null for some reason.
        NSLog(@"Delegate method not getting called...%@",delegate);
    }
}

in MyTableViewController.h

@interface MyTableViewController : UITableViewController

MyTableViewController.m

-(void)addItem:(myFormViewController *)formViewController itemToAdd:(Item *)item{

    if(item)
    {
        MyClass *_itemClass = [[MyClass alloc]initWithPath:@"items/"];

        [_itemClass addItemForUser:item];
    }

    [formViewController dismissViewControllerAnimated:YES completion:nil];
}

in my prepareForSegue method I am setting my tableviewcontroller as delegate.

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

   if ([segue.identifier isEqualToString:@"addItemSegue"]){

    myFormViewController *_showaddTopic = [[myFormViewController alloc]init];

    _showaddTopic.delegate = self;
}

After all this, my delegate in myFormViewController is being set to "null". I am not sure why it's not working. It's pretty basic stuff but giving me hard time.

Thank you

Upvotes: 2

Views: 2040

Answers (2)

RZMars
RZMars

Reputation: 125

maybe _showaddTopic.delegate = self; can not written here and shuold this object alloc after at once

Upvotes: 0

matt
matt

Reputation: 535306

myFormViewController *_showaddTopic = [[myFormViewController alloc]init];
_showaddTopic.delegate = self;

There's your problem. You are creating a new MyFormViewController. But that's the wrong MyFormViewController; you want to use the one that is already the segue's destination controller. So you are setting the wrong object's delegate.

(PS Notice my use of a capital letter to start the name of a class? Always do that.)

Upvotes: 4

Related Questions