performSelectorInBackground, notify other viewcontroller when done - iphone

I have a method used to save an image when the user clicks Save.
I use performSelectorInBackground to save the image, the viewcontroller is popped and the previous viewcontroller is shown.
I want the table (on the previousUIViewController) to reload its data when the imagesaving is done.
How can I do this?
The save method is called like this:
[self performSelectorInBackground:#selector(saveImage) withObject:nil];
[self.navigationController popViewControllerAnimated:YES];

In your saveImage method, post a notification just after finishing saving the image and before returning from the method. Something like this:
// post notification
[[NSNotificationCenter defaultCenter] postNotificationName:#"ImageSaved" object:nil];
In the controller handling the table, implement
- (void) imageSaved:(NSNotification *)notification{
[self.tableView reloadData];
}
and in its viewDidLoad method add the following code to register for notifications:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(imageSaved:)
name:#"ImageSaved" object:nil];
finally, unregister in the dealloc method adding
[[NSNotificationCenter defaultCenter] removeObserver:self];

I think the way to go is calling the method at the end of the saveImage routine. Maybe something like
[self performSelectorInBackground:#selector(saveImage) withObject:previousView];
And if you want to keep saveImage agnostic, create a protocol with a callback that your previousView can use.
#protocol processingFinishedDelegate
-(void)processingFinished;
#end
so At the end of saveImage you'll have:
[(id<processingFinishedDelegate>)object processingFinished];
and of course your previousView class interface should handle the delegate.

I am having problems using this to update UITextView with the approach "unforgiven" suggested. I tried couple of different ways but all failed... I also tried notifications + observers with this but no success... Why is that? It is working fine on UILabel but no UITextView with this message:
Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...

Related

NSNotificationCenter with respect to ViewWillAppear and ViewWillDisapper

I have a simple viewController that I want to listen for UIKeyboardWillHideNotification. Therefore I have the following code:
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillBeHidden)
name:UIKeyboardWillHideNotification object:nil];
}
- (void) keyboardWillBeHidden
{
[self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}
I'm trying to decide when to remove the viewController as an notification center observer. I only need to know about the UIKeyboardWillHideNotification when the viewcontroller is on screen, thus I'm thinking about adding the following:
- (void) viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Is this sufficient? Is there ever a chance that viewDidUnload or dealloc will get called while the viewController is still on screen? Note that I'm using a very basic UINavigationController for the flow of my app.
Registering the notification in viewWillAppear and unregistering it in viewWillDisappear seems to be a clean and symmetric solution to me.
Note that viewWillAppear can be called multiple times before dealloc (e.g. if another view controller is pushed onto your VC, or if you switch between tab bar controllers.) If you register the notification in viewWillAppear and unregister it only in dealloc then you will get duplicate registrations (compare Warning for iOS/iPhone users about duplicate NSNotification observations) and the registered selector is called multiple times for a single notification event.
I actually prefer the block-based observer registration method
addObserverForName:object:queue:usingBlock:
which returns an opaque object which is used for removing the observer again. Storing this return value into an instance variable of your view controller helps to keep track if the observer is already registered or not, and therefore helps to avoid duplicate registrations.
To answer your direct question, dealloc will never be called while your view is still on screen unless you directly call it which you shouldn't be.
dealloc will only be called when there are no strong pointers remaining that point to your viewController.
As Anoop Vaidya suggests, it is totally doable to put removeObserver in dealloc and be confident that dealloc won't get called while your viewController is on screen, and if it does... well you have much bigger problems than removing an observer
Edit: Since I can't actually reply to comments yet, when your viewController is off screen it is actually deallocated. It is then re-instantiated when it is called back on screen.
Edit: I'm wrong

No code executed inside NSNotification handler method even the method is called properly

I've strange problem. In ViewController.m, I post notification after successful save and perform Segue to ListViewController. In ListViewController.m, I set up observer in viewDidLoad and declare method for handling.
The problem is that handler method is called but no code inside is executed! Any idea why?
// ViewController.m
if (success) {
[[NSNotificationCenter defaultCenter] postNotificationName:kAHPlistSavedSuccessfully object:self];
[self performSegueWithIdentifier:kAHDetailToListSegue sender:self];
}
// ListViewController.m
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(plistSavedSuccessfully:) name:kAHPlistSavedSuccessfully object:nil];
}
- (void)plistSavedSuccessfully:(NSNotification *)notification
{
NSLog(#"notification %#", notification);
[self someMethod]; // not called !
}
I can spot a few things that might be at fault.
Firstly, you post the notification before you perform the segue to the list view controller, so it's possible that the notification is posted before the list view controller adds itself as an observer for the notification. (Unlikely because the log statement is printing, but still possible in some cases).
The second thing is that notifications are received on the same queue as the one they are posted on. Is it possible that your post notification code is called on different queue to the main queue? This might cause problems if someMethod does any work with code that isn't thread safe. You should verify which queue your post notification code is called on, and either ensure that it is called on the main queue, or in your handler, dispatch the call to someMethod to the main queue using dispatch_async.

What's the better way to addObserver/removeObserver with NSNotificationCenter?

I used to addObserver in viewDidLoad: and removeObserver in dealloc:. Code:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(refreshData)
name:AnyNotification
object:nil];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:AnyNotification
object:nil];
}
But according to some articles said, it's better to addObserver in viewDidAppear: and removeObserver in viewDidDisappear:. Code:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(refreshData)
name:AnyNotification
object:nil];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:AnyNotification
object:nil];
}
So, what's the better way to addObserver/removeObserver?
this depends on your scenario, usually the best approach is to add in viewDidLoad and remove in dealloc and in viewDidUnload (deprecated in iOS 9.0, use dealloc only), but there are some cases when you have same method in different classes like UI effects and want to call only current screen's method using notification, then you will have to add the observer in viewWillAppear and remove it in viewWillDisappear or viewDidAppear/viewDidDisappear
Edit:
A note from comments, thanks #honey.
Though now since iOS 9, you no longer need to care about removing the observer. See Apple release notes: "In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated..
I would normally put it in -viewDidAppear: and -viewDidDisapear: (or -viewWillAppear: and -viewWillDisappear:) simply because in every case I came across I'm only interested in the notification if the view is actually displayed.
It's probably a premature optimisation (your code for handling the notification could take some time, but might be useless if the view is not displayed), but then it's also no more code - it's the same code just in a different method...
Don't forget NSKeyValueObservingOptionInitial. I use it with viewWillAppear/viewWillDisappear so my UI is always up-do-date, even if I hide that view controller, saving resources because I will not update it until is shown again.
The best approach using NSNotifications is adding the observer when you need to observe for notifications and remove them when you don't need them anymore.
This could be on viewDidLoad:, viewWillAppear:, or when the user taps some button etc.
I will give you a little example:
My app has a tabbar, and in some of the view controllers, I'm displaying some info downloaded from internet (a tweet for example). I also have a class pooling for new data from server each 2 minutes, and as the server had new data, I updated the info on database. I will not use a delegate pattern to listen to DB changes, because I have so many view controllers displaying data, and it will be a very bad design making the delegate an array and looping to pass the data for every view controller. So, in this specific scenario, the best to do is to post a notification telling every VC that new data has come.
If your VC removes the delegate when the view disappears, only the current one will receive the notification and update the displaying contents.
You obviously could update the contents of the other VCs before display, on viewWillAppear: for example, but doing this the VC contents will be updated not only when necessary, but each time you change tabs.
It was only one example, where I tried to show you that for NSNotifications, is difficult to advise you when to add or remove observers when we don't have the entire description of how you app behaviours.
-viewWillAppear: + -viewWillDisappear: is better than -viewDidAppear: + -viewDidDisapear:, because they are always called the same number of times.

nsnotificationcenter method fired more than once

i have a viewcontroller .In it there is a nsnotification observer in it. i am posting the notification from another viewcontroller.but the nsnotification observers selector get fired two or sometimes three times. My question is that when i use [view removeFromSuperview];
to remove this viewcontrollers view ,is the notification observer removed? I have given this method at the dealloc method of the viewcontroller class
- (void)dealloc {
[super dealloc];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
No.
that method will be called when the viewcontrollers retain count becomes 0
You should add another method that will be called when the view is removed from the other viewcontroller and call
[[NSNotificationCenter defaultCenter] removeObserver:self];
For the issue that the selector is called multiple times, I would need to see more code - make sure that the line of code thats posting the notification isnt being called multiple times
NSNotification registered to whole app (or even for all operating system), not to single view or viewcontroller. You have need for remove observer in your action if it won't longer used. In this case you can handle only one posted notification.

Reloading TableView on iPhone from another class

So I have a FirstViewController, which is a UITableViewController, as well as delegate and dataSource. It has the table view.
I have another class, FeedParser, that parses the data - but after it's done parsing, I need it to go and refresh the UITableView or else it won't show anything.
This is probably a stupid question, so forgive me, but how should I go about calling FirstViewController's tableView.reloadData from FeedParser?
Is there a method to return that view?
Thanks!
Register the view controller to receive notifications that the data has been changed, and have it refresh the table when it receives one. Then have the parser send it out.
Registering for it is easy:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(yourRefreshMethodHere:)
name:#"YourNotificationName"
object:nil];
Your refresh method needs to be set up to receive these notifications, along these lines:
- (void)reloadTable:(NSNotification *)notif {
[self.yourTableName reloadData];
}
And it's important to stop observing in your ViewDidUnload:
[[NSNotificationCenter defaultCenter] removeObserver:self];
Then in the parser you need to simply add this when it's complete:
[[NSNotificationCenter defaultCenter] postNotificationName:#"YourNotificationName"
object:nil];
The view controller (and anyone else observing the notification with that name) will get the message and perform its task.
Simple method,
Create a object for your FirstViewController in appDelegate, assign property and synthesize it.
In ViewDidLoad of FirstViewController,
firstViewControllerObj = self;
In feedParser.m, after the parsing done code as follows,
[appDelegate.firstViewControllerObj.tabelView reloadData];
Just store a reference to FirstViewController on your app delegate, then call [appDelegate.firstViewController.tableView reloadData].