E A
E A

Reputation: 93

What is the proper way to implement MVC pattern in iOS app?

I'm trying to make a clean MVC project. So is it good or bad idea to use NSNotificationCenter's observers for communication between UIViews and ViewControllers?

For example in the CustomView.m i make a button:

- (void) makeSomeButton{
....
 [bt addTarget:self action:@(buttonWasClicked) forControlEvents:UIControlEventTouchDragInside];
...
}

- (void) buttonWasClicked {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"buttonWasClicked" object:nil];
}

And in the viewCotroller.m i'm adding observer in init section:

- (void)viewDidLoad {  // 
       [self.view addSubview: [[CustomView alloc] initWithFrame ...]];     
       .....
         [[NSNotificationCenter defaultCenter] addObserver:self
         selector:@(buttonWasClicked) name:@"buttonWasClicked" object:nil];
       .....
    }

    then 
    - (void) buttonWasClicked{
     // button was clicked in customView so do something 
    }

If it's not correct, please, explain what is the proper way to implement MVC pattern in iOS app?

Upvotes: 0

Views: 193

Answers (1)

Callum Boddy
Callum Boddy

Reputation: 407

No, Notification Center shouldn't be used in this scenario.

The pattern I would use here is delegation.

in your CustomView, declare a protocol, with some method,

at the top of your header:

@protocol CustomViewDelegate : NSObject

- (void)customViewDidSelectButton;

@end

in the interface.

@interface CustomView : NSObject

---

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

---

@end

in the implementation:

- (void) buttonWasClicked {
 [self.delegate customViewDidSelectButton];
}

In the View Controller Observing

in the implementation file add <CustomViewDelegate> (same place you put TableViewDelegate etc..)

and then when you create the CustomView set is delegate to self.

implement the delegate method:

 - (void)customViewDidSelectButton {
     // button was clicked in customView so do something 
}

Upvotes: 2

Related Questions