iOS: Notify other tabbed view controllers about a change in its dataset - iphone

I have a tab bar controller and inside it two controllers: a mapview controller and a tableview + NSFetcheddata controller. Both display info about a specific day from core data and have a button to display a day selector modally.
I have achieved having my controllers dataset changing when their modal view controller disappears through delegation but I would like the two controllers to update their data and not only the one who displayed the modal controller.
I thought about creating a protocol in both controllers and setting each other as its delegate but I would like to know if I'm doing right here.
Cheers,
Thierry

There are tons of different ways to do this. One way is to use NSNotificationCenter. Define your own custom notification name:
static NSString *const CSDataUpdatedNotification = #"CSDataUpdatedNotification";
Subscribe to this notification in both of your controllers:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(dataUpdated:) name:CSDataUpdatedNotification object:nil];
And implement dataUpdated: to update your data:
- (void)dataUpdated:(NSNotification *)notification
{
// Handle updates here
}
In the controller causing the change, post the notification:
- (void)updateData
{
// Data updating routine
// ...
[[NSNotificationCenter defaultCenter] postNotificationName:CSDataUpdatedNotification object:self];
}

You could set both as the delegate (i.e. two delegates) and re-use your modal view controller for both.
Alternatively, use NSNotificationCenter, but I think the delegate method is better, because the relationship is closer this way. which is the way to go if you want to message more than one object.

Thierry,
being new to iOS, I wouldn't call this an "answer", but using a global notification system does not sound right for this kind of problem to me.
Looking for an answer to a similar problem, I stumbled over references to NSFetchedResultsController, which will calculate results for you, readily to be used as a UITableView model - only reading knowledge. The part relevant to your problem seems to be its delegate, NSFetchedResultsControllerDelegate, which defines a few methods which will allow to communicate changes to the result to any number of interested parties.
But as I said, I just stumbled over it, and are just now trying to make use of it.
Regards, nobi

Related

How does iOS decide which objects get sent didReceiveMemoryWarning message?

I am working on an iPhone application in which a number of UIViews are dynamically added to and removed from the main UIWindow.
When simulating low memory errors in the simulator, I have discovered that not all view controllers receive the didReceiveMemoryWarning notification. Unfortunately, these are the controllers that would most benefit from implementing this method.
I cannot seem to find good information about where and how the method gets called. I have read mentions that it gets sent to "all UIViewControllers", but this is evidently not the case. Adding a breakpoint in one of the classes that do receive the notification wasn't particularly enlightening either.
This is a complex project but one way these views get added is:
- (void) showMyView
{
if(!myViewController){
myViewController = [[MyViewController alloc]init];
[window addSubview:myViewController.view];
}
}
MyViewController is a subclass of another class, MySuperViewController, which is itself a subclass of UIViewController. None of those classes have corresponding NIBs; view hierarchies are created programatically.
I am looking for pointers to how I can go about diagnosing the problem.
When you are using .view of the view controller directly, there's a high chance that your view controller won't receive many notifications because it's not the correct way of using view controller. The UIWindow is special case, because the window can automagically know the controller of the view and direct the message to the controller correctly.
However, when you detach your view from UIWindow, the view controller is also detached and not managed by UIWindow any more. I think this is the source of the problem.
I would suggest that you add a navigation controller or tab bar controller as your root view controller, and use that view controller functionality to switch between your child controllers. Note that you should not remove your view controllers when switching so they will be able to receive the messages appropriately.
You might also considering releasing your view controller when not used if initialization of your view controller is trivial and not consuming too much time.
Somewhere in your code you are probably doing something like this:
[[NSNotificationCenter defaultCenter] removeObserver:self];
The only safe place to do this is in -dealloc.
Everywhere else, you should specify the notification that you want to unregister for (this will still potentially break if you register for the same notification as a superlcass).
From the documentation
The default implementation of
[didReceiveMemoryWarning] checks to
see if the view controller can safely
release its view. This is possible if
the view itself does not have a
superview and can be reloaded either
from a nib file or using a custom
loadView method.
This method gets called when a Memory Warning "happens"/is simulated. When the memory is low, the system probably posts a notification and a view controller responds to the notification by calling didReceiveMemoryWarning.
If you do not override the method, the default implementation (described above) is called. All view controllers in memory receive the Memory Warning and call this method. They just don't do anything if it is not "safe" to release the view.
In a simple test application with a navigation controller, in both the current view controller and the one previously displayed, didReceiveMemoryWarning is called. I don't know how the NSNotificationCenter works exactly, but it knows who registered for the UIApplicationDidReceiveMemoryWarningNotification. It is probably set up something like this:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(didReceiveMemoryWarning)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
For more information, you can look at the Memory Management section in the UIViewController Class Reference.
I entered this question, searching for the right observer dealing with memory warnings. For those using swift, you can register as followed:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveMemoryWarning:", name:UIApplicationDidReceiveMemoryWarningNotification, object: nil)
With callback method:
func didReceiveMemoryWarning(notification: NSNotification){
//Action take on Notification
}
Also, make sure your custom class inherits from NSObject, or you'll be getting this error:
… does not implement methodSignatureForSelector: — trouble ahead

Objective-C object dealloc'd while other objects still has a delegate reference to it causes crashes. How to prevent this?

I have an app with a navigation controller as the root view. There are many views that can be pushed in.
The user has to create an account to use the app. The user can then log into this account from other devices, but only one device can be logged onto the same account at a time. So if multiple devices try to log into an account, only the latest device will be logged in and the other devices are logged off (a push is sent to the devices).
Since there are multiple views that the device could be showing before it was logged off, I call popToRootViewControllerAnimated: to get back to the root view. This is because when the user logs in the next time I only want the root view to be shown (the new account might not have access to the previously shown view).
If the user has an alert view or action sheet presented (which uses the current view as its delegate) before the push is received, the view will still be shown after the popToRootViewControllerAnimate: method is called. If the user then taps on a button for the alert view or action sheet, it will send a message to the dealloc'd view and crash the app.
An example:
myViewController is being shown to the user.
myViewController create an action sheet prompting the user for a decision.
The push is received for the device to log out.
The navigation controller pops all the views controllers and now shows myRootViewController.
Since the view controllers are popped, myViewController is now dealloc'd.
The action sheet from myViewController is still shown.
When the user selects an option form the action sheet, a message is sent to myViewController, and since it is already dealloc'd, a crash will occur.
Is there any way to prevent this?
One solution I have considered would be to keep track of all the objects that uses a specific view controller as its delegate. Then when that view controller dealloc's it will also set all the object's delegates to nil. This requires me to manually take care of every view controller when they create an object that uses itself as the delegate, since I cannot think of a way to automatically create and update this list.
Any better solution (or improvement to mine) would be appreciated!
Edit: The alert view and action sheet are only examples of some objects that I would use myViewController as a delegate. I am also using a number of other classes (and third-party libraries) that implements this delegate pattern.
A few ideas:
you can encapsulate the alert/action sheet view and delegate in a single class. Then when you need an alert view, create MyAlertView instead, which will also be its own delegate and will do [self release] after the user taps a button.
make your App Delegate the only delegate for all your alert views and action sheets. App Delegate is always around while the application is running, so there won't be a problem with a released delegate.
The problem with both solutions is that if you need your application to know what happened in the alert view/action sheet, you somehow need to tell the interested class of the user's choice.
You can do that by either using delegates of your own - which would mean you're back to square one - or use notifications: when the alert view/action sheet delegate is called, it would post a notification ([[NSNotificationCenter defaultCenter] postNotificationName:NotificationName object:self userInfo:userInfo];), while the interested object would look for that notification ([[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(onNotification:) name:NotificationName object:nil];) and perform whatever tasks necessary in onNotification:(NSNotification*)aNotification method.
You'll be able to agree with yourself on what type of information is passed in those notifications (I would think the button number in a NSNumber class would be enough, or perhaps pass the button text, too). And you won't have to keep track of all alert views - just don't forget to remove the observer ([[NSNotificationCenter defaultCenter] removeObserver:self name:postNotificationName object:nil];) in the views' dealloc.
Edit:
"This requires me to manually take care of every view controller when they create an object that uses itself as the delegate, since I cannot think of a way to automatically create and update this list."
Actually you probably can do this in a semi-automated way: make a singleton object with a method like
-(id)delegate:(id)delegate for:(id)forWhom
And then instead of
someThingy.delegate = self;
you'd do
someThingy.delegate = [[DelegateLocker defaultLocker] delegate:self for:someThingy];
Inside the DelegateLocker you'd have a MutableDictionary with delegate class as a key and a MutableArray of someThingies as a value. Then in your view controllers' deallocs you'd call
[[DelegateLocker defaultLocker] delegateIsDying:self];
which would go through the thingies and assign delegate = nil for each
The drawback of course is that you'll be retaining all the thingies for an indefinite period of time instead of releasing them immediately.
So the ViewController that presented the action sheet iand set itself as the delegate right? So why dont you keep a reference to the ActionSheet in the ViewController, in the dealloc method of the view controller, you can check if the action sheet is visible, if it is then set the delegate of the action sheet to nil,and dismiss it...
so
-(void)dealloc
{
if(myActionSheet && [myActionSheet visible])
{
[myActionSheet setDelegate: nil];
//dismiss
}
}
Hope that helps
If you want automated solution, I think you can make a function to iterate through Ivars of your view controller to see if any Ivar has delegate property and set it to nil.

sending data to previous view in iphone

What are the possible ways to send data to previous view in iphone. Without using Appdelegate. Because there are chances for my view class to be instantiated again.
I believe the best approach is using the NSNotificationCenter class.
Basically what you do is register an object (as an observer) with a notification center.
So for example if you have objects A and B. A registers as an observer. Now lets say A is the "previous" object you are talking about, you can have B send a notification (data or message) to the notification center which then notifies object A (and any other registered observers).
Example:
In file ClassA.m register as shown below:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didSomething:) name:#"SomethingHappened" object:nil];
didSomething is the method which receives the notification sent by object B. This will look something like
- (void) didSomething: (NSNotification *) notify {
...
}
Finally you send the message below from whatever method in ClassB.m to notify/send data to object A
[[NSNotificationCenter defaultCenter] postNotificationName:#"SomethingHappened" object:self userInfo:your_data];
Seems convoluted but it's the best approach in my opinion (and quite simple once you understand it :)).
There are several ways to achieve data sharing, with Singleton Objetcs being one of the most popular:
Objective C Singleton
If the view you want to communicate with is a parent view (e.g. the previous view's view controller is where you created this view) then you probably want to handle dismissing the view in the previous view controller. When you do that, you can read the data that has changed and update the previous view controller with the new data.
Then in the viewWillAppear: method of the previous view controller, update the actual views to reflect the current state of the view controller.
Edit: I've just noticed that your newView is transparent. If this is the case, then you certainly want to route all logic through your view controller. You should only have one view controller with visible views at a time.

iPhone updating view

I am trying to solve a problem considering update of an view.
First I switch to another view by using:
- (void)viewSettings {
settingsViewController = [[SettingsViewController alloc] initWithNibName:nil bundle:nil];
[[self viewController] presentModalViewController:settingsViewController animated:YES];}
Which is a delegate Method called by
ivaskAppDelegate *mainDelegate = (ivaskAppDelegate *)[[UIApplication sharedApplication] delegate];
[mainDelegate viewSettings];
I switch back by calling another dellegate method
- (void)settingsDone {
[[self viewController] dismissModalViewControllerAnimated:YES];}
When I return to my view I now want to update a label, can you explain how to do it?
I use NIB-files which have a controller class and a view class connected in the identity inspector.
/N
Although I heavily suggest delegation in this case there are two other options, that come to my mind: Notification and KVO.
Notification
Whenever settings are changed the settings view controller could post a Notification, to let other parts of the app know about this change. Posting a notification is easy as:
[[NSNotificationCenter defaultCenter]
postNotificationName:#"SettingsChangedNotification" object:theNewSettings];
Every object that somehow want to know about a settings change can subscribe to that notification via:
//Subscribe (in viewDidLoad or init)
[[NSNotificationCenter defaultCenter]
addObserver:self selector:#selector(settingsChanged:)
name:#"SettingsChangedNotification" object:nil];
// Called when a "SettingsChangedNotification" is posted
- (void)settingsChanged:(NSNotification*)settingsChangedNotification {
id newSettings = [settingsChangedNotification object];
}
//Unsubscribe (in viewDidUnload or dealloc)
[[NSNotificationCenter defaultCenter]
removeObserver:self name:#"SettingsChangedNotification" object:nil];
See Notification Programming Topics
If you are trying to manages UserDefaults with your settingsViewController there's an even better way. Just set the values on the sharedUserDefaults and the app will post a NSUserDefaultsDidChangeNotification notification all on it's own. All objects that depend on user settings could subscribe to that notification, and after it's posted reread the userDefaults.
See
NSUserDefaults Class Reference
User Defaults Programming Topics
Key-Value Observing (KVO)
Your rootViewController could observe changes of an object, which it needs to synchronize with, by Key-Value Observing.
One object registers itself as observer for keyPaths on other objects by sending them a addObserver:forKeyPath:options:context: message. The object is informed about changes via the observeValueForKeyPath:ofObject:change:context: callback method. KVO could sometimes be difficult the get right, because you have to ensure, that you register and unregister the same number of times, before an object gets deallocated.
See Key-Value Observing Programming Guide
Conclusion
Please refrain from using "global" variables on your app-delegate. There's enough possibilities to do better. The sooner you dive into them, the better code you will write.
You will need to set up a delegate that is implemented in your main view controller (where you need to have the label updated), and that is called from your settings view controller. I have a blog post that describes how to do this:
http://www.dosomethinghere.com/2009/07/18/setting-up-a-delegate-in-the-iphone-sdk/
You would make your view controller conform to a protocol that your create. In this case it may be named SettingsDelegate. That protocol contains one message - (void)didFinishSettingsWithSomeNewValue:(id)newValue;
The Settings Controller has a delegate instance variable and a property of type id<SettingsDelegate>
Before you present the settings viewController you assign the parent view controller to the delegate property. In the settings view controller you send a didFinishSettingsWithSomeNewValue: message to your delegate (the parent view controller) along with some new value. The parent view controller implements that method and inside the implementation can dissmiss the modal controller and update any views on itself.

iPhone UITableView trigger a parent method?

Okay, so I'm working on an iPhone app with a preferences-esque section where there's a base TableView, which has one section, and several rows of customized cells to hold a name and a value label. Clicking on a row brings up another View, which allows the user to pick from a list (another TableView), and select an item.
All of these TableViews are done programatically. The base TableView has a property that holds a Controller instance for each of the "pick from the list" Views. Each of the "pick from the list" views has a property called chosenValue that has the currently-selected option. I've gotten the UI to handle the didSelectRowAtIndexPath to update the chosenValue property and then "pop" the view (going back to the main TableView). But, even though the main TableView's cellForRowAtIndexPath method references the chosenValue property of the subview that's held in a property, the view doesn't update when an item is selected. In short, how can the sub-view trigger a reloadData on the parent object, after it "pops" and unloads?
You could realize this using the notifications or delegation, for example.
Using notifications your first view controller has to register for a notification like this:
…
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(methodToBeCalled:)
name:#"myNotification"
object:nil];
…
- (void)methodToBeCalled:(NSNotification *)notification {
[self.tableView reloadData];
// do something else
}
Then you can raise a notification in your second view controller like this:
[[NSNotificationCenter defaultCenter] postNotificationName:#"myNotification" object:nil];
Using delegation you could implement a property for a delegate on the second view, set that to self before pushing the second view controller and call a method on the delegate when needed.
You should define a delegate for that.
In the child TableView define a protocol:
#protocol ChildViewControllerDelegate
- (void) somethingUpdated;
#end
Also define a property for a delegate implementing this protocol:
id <ChildViewControllerDelegate> delegate;
Then in Parent all you need to do is to define a method somethingUpdated, assign itself (parent) to a delegate property in Child and call this method in Child view when you need to update it. Implementation of somethingUpdated in Parent can be different based on what you're trying to accomplish.
flohei thanks so much for posting this!! I got it working with NSNotificationCenter! I have a child view calling a method in a parent view now! Awesome. #sha I tried your protocol way also but could not figure it out. Perhaps a more illaborate discription would help a noob like me. I have been reading that your protocol way is the better cause I guess less code? So i'll try to keep learning it. Thanks to you both!