user1992596
user1992596

Reputation: 5

1 delegate to 3 view controllers

I have a cameraViewController that is essentially a barcode scanner. I also have 3 view controllers (A, B and C) each with a button that lead to this cameraViewController.

When cameraViewController scans a barcode, it does the following:

if (self.detectionString != nil)
    {
        [self.delegate cameraViewController:self withCardNumber:self.detectionString];
        [self.navigationController popViewControllerAnimated:YES ];

        break;
    }

It has a delegate and sends the detected string back to the previous/parent view controller. All three viewControllers have the following methodimplemented:

#pragma mark - CameraViewControllerDelegate

- (void)cameraViewController:(CameraViewController *)cameraViewController withCardNumber:(NSString *)number
{
self.CardNumbertext.text = number ;
}

So both methods work with cameraViewController and viewControllerA. However, when the parentViewController is B or C, the cameraViewController still pops back to the right controller but the delegate function does not run. What am I doing wrong?

Upvotes: 0

Views: 110

Answers (3)

esreli
esreli

Reputation: 5071

Post a notification to NSNotificationCenter, it's a much better solution to this problem :)

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html

Upvotes: 0

rustylepord
rustylepord

Reputation: 5801

If you want keep the current implementation then update the delegate when you are presenting ViewController A,B and C. From the way you described in the question seems like you need to do this in -(void)viewWillAppear or -(void)viewDidAppear. Or use the notification manager as the OP suggested or else use blocks.

Upvotes: 0

RobP
RobP

Reputation: 9542

It's iffy to have just one instance of cameraViewController and three different view controllers that "fight over it" by each setting the cameraVC's delegate to themselves. I think it's a better use of system resources and better architecture if each of the A, B, C viewcontrollers responds to the button press by instantiating a new instance of CameraViewController and setting that instance's delegate to self. This should fix your issue and improve memory management/leak issues as well.

Upvotes: 1

Related Questions