xiaogang
xiaogang

Reputation: 3

how to manage viewControllers in iOS

I have a problem with transfering data between viewcontrollers. I`m now working on a small app, it has a main viewcontroller,and in this viewcontroller user can change some global data that all other viewcontrollers will use to fetch data from the internet. So, when the global data changes I need to tell other viewcontrollers to update data.

The question is how can I tell other viewcontrollers when the global data changes?

I know I should use NSNotificationCenter to solve this problem, but I feel notification is like a foreigner to all the viewcontrollers.

What I want to do is to add a ViewControllerManager to manage all the viewControllers. Firstly, I would add all the viewcontroller who need to use the global data to the manager. Then ,when the global data changes I could find these viewcontrollers through the manager,and notify them to update the global data directly.

and this is my @interface.

@interface ViewControllerManager : NSObject
+ (ViewControllerManager *)sharedManager;
- (void)addViewController: (UIViewController *)viewController;
- (void)removeViewController: (UIViewController *)viewController;
- (void)removeViewControllerByClass: (Class)aClass;

- (UIViewController *)viewControllerByClass: (Class)aClass;
- (NSArray *)viewControllersByClass: (Class)aClass;

//get viewcontrollers who can response to selector, so I can send them this message.
- (NSArray *)viewControllersResponseTo: (SEL) selector;

//get current visible viewcontroller.
@property (nonatomic, retain) UIViewController * visibleViewController;

@end

It works well, through this manager I can get any viewcontroller I want, and I can transfer global data easily between viewcontrollers, But the problem is I don't know how to manage the memory correctly, in method [ViewControllerManager addViewController: ], I retain the viewController ,But I don`t know when to release it ,so this viewController will never be dealloc...

Upvotes: 0

Views: 154

Answers (2)

xiaogang
xiaogang

Reputation: 3

Finally , I solved this problem by using weak reference, and this is the code: https://github.com/github-xiaogang/ViewControllerManager

Upvotes: 0

Zeke
Zeke

Reputation: 134

The latest point in time where you have a possibility to release is in your manager class's dealloc method. If you store those controllers in an array at the moment of adding them the array also retain them. It might be a solution to retain and release that array only, not the controllers. When an item is removed from an array the array does the necessary releasing. Also when an array is gone (released), the items are gone as well (automatically).

By the way what you are doing is called Mediator pattern I think. The controllers talk only to a central object not to each other. Only the mediator knows all the actors.

Upvotes: 1

Related Questions