iPhone updating view - iphone

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.

Related

Call popViewController from Class Method

I'd like to go back to my root view from within a class method of view 1. When in an instance method of view 1, i would just say
[self.navigationController popViewControllerAnimated:YES];
but since self doesn't apply in a class method, I am wondering how to accomplish this. Pertaining to the illustration below, I am currently in a class method of View1Controller.m and I'd like to get back to Rootview. Thanks.
You can declare another method:
-(void)closeThisViewController
{
[self.navigationController popViewControllerAnimated:YES];
}
Then use NotificationCenter:
[[NSNotificationCenter defaultCenter] postNotificationName:#"notif_closeThisVC" selector:#selector(closeThisViewController) object:nil];
Although as jonkroll said, you're dealing with view controller stuff, we don't understand why you would put view controller related code inside a class method.
Edit
Sorry bad code above.
I meant to say you can use NSNotificationCenter to post a notification:
-(void)postNotificationName:(NSString *)notificationName object:(id)notificationSender
Then in the same view controller declare a NSNotificationCenter observer:
- (void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender
My brain was quicker than my fingers, so I kinda combined the two into one when I tried to explain the solution :P
It should more like this:
// posting a notification with NSNotificationCenter
[[NSNotificationCenter defaultCenter] postNotificationName:#"notif_closeThisVC" object:nil];
In your viewDidLoad method somewhere (I recommend at the top), add this:
-(void)viewDidLoad
{
// adding an observer with NSNotificationCenter
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(closeThisViewController) name:#"notif_closeThisVC" object:nil];
...
}
Hope that helps.
If you don't want to refactor this from a class method to an instance method (and there are certainly cases where you wouldn't want to do that), I'd suggest you add a completion block parameter to your class method:
+ (void)doSomethingWithCompletion:(void(^)())completion {
/* Do your thing... */
completion();
}
- (IBAction)doSomething:(id)sender {
[self.class doSomethingWithCompletion:^{
[self.navigationController popViewControllerAnimated:YES];
}];
}
This would allow you to cleanly separate the instance-less operation the class method performs from instance-specific dismissing of the view controller. You could also make the completion block accept an error object if the operation can fail.
You could do something similar with a delegate object or even by passing in the view controller to dismiss, but this design seems to offer the cleanest separation with the most modern feel.
There are going to be legitimate arguments that encourage you to refactor so that you do have access to the current view controller and can access the navigation controller via currentVC.navigationController. Remember, it can still be a class method, just give it an extra argument when you call it (or start the call chain that calls it) from the VC.
However, I also had to solve this in one of my apps, so I just made sure that the navigation controller was globally accessible to everyone, always via pointer ("weak ref")
If you declare a global variable like this (say, in "Navigation.h")
extern UINavigationController *gNavController;
and define it in your AppDelegate.m (pays to review distinction between declaration/definition if you're rusty on that):
UINavigationController* gNavController;
and then assign it when you start up in application:didFinishLaunchingWithOptions::
(assuming the delegate has a property called viewController that is your navigation controller):
gNavController = viewController;
Then as long as you #import Navigation.h, you'll always have access to the navigation controller. This also makes getting a handle to its view for popups/popovers much simpler.
This also assumes your nav controller is never released for the lifetime of the app (probably true unless you're doing something unusual).

Changing view from within didReceiveRemoteNotification

Being still new to iPhone development, I am slowly getting there however sometimes the simple things seem to stump me.
My application consists of 7 very different views. It is implemented as a window based app without a navigation controller. Navigation is managed by each view controller individually and I use a central data repository to make data available through the app.
I use :-
DetailView *viewDetail = [[DetailView alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:viewDetail animated:YES];
to change views. Obviously, in all cases, this is executed within the controller of the current view.
HOWEVER, I have now added Push Notification to the app. Upon receipt of a Push, the userInfo data is made available within the main AppDelegate and didReceiveRemoteNotification is executed. I wish to force the application into the Detailview described above, passing it one of the values within userInfo.
Of course, I get a nice SIGABRT as soon as it executes the second line. I assume this is because the currently active view is not self. How do I surrender the current view in favour of the DetailView from within the app delegate? The current view could be ANY of the 7 views, including DetailView, which I wil want to refresh with the new data.
Thanks in advance
Chris Hardaker
This is a small side note, but the naming convention that you are using is non-standard. Rather than,
DetailView *viewDetail = [[DetailView alloc] initWithNibName:nil bundle:nil];
conventionally, an iOS developer would expect to see the following:
DetailViewController *viewDetail = [[DetailViewController alloc] initWithNibName:nil bundle:nil];
since viewDetail is a subclass of UIViewController rather than UIView.
To answer you main question though, I would use NSNotificationCenter. Basically, this allows any class to post a notification, which more or less just throws out the fact that an event occurred to any class that happens to be listening for it.
So in didReceiveRemoveNotification: you can call:
[[NSNotificationCenter defaultCenter] postNotificationName:#"pushNotification" object:nil userInfo:userInfo];
When you allocate your view controllers, run this line:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(pushNotificationReceived:) name:#"pushNotification" object:nil];
You will need to put a method called pushNotificationReceived: (NSNotification*)aNotification in each of the view controllers to handle the notification. The userInfo dictionary that you passed will be a property of the notification.
Now, when ever the #"pushNotification" notification is sent, your controllers will receive a notification and run the given selector. So you can dismiss the controller or show the detail view or whatever you want.
When you dealloc your view controller, make sure to call
[[NSNotificationCenter defaultCenter] removeObserver:self];

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

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

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

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.