I have a situation in which it can happen, that the last strong reference to an observer is removed while the observer processes an incoming notification.
That leads to the observer being deallocated immediately. I would normally expect, that a currently running method can finish before an object is deallocated. And this is what happens during normal message dispatch.
A simplified version of the code:
TKLAppDelegate.h:
#import <UIKit/UIKit.h>
#import "TKLNotificationObserver.h"
#interface TKLAppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) TKLNotificationObserver *observer;
#end
TKLAppDelegate.m:
#import "TKLAppDelegate.h"
#implementation TKLAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Create an observer and hold a strong reference to it in a property
self.observer = [[TKLNotificationObserver alloc] init];
// During the processing of this notification the observer will remove the only strong reference
// to it and will immediatly be dealloced, before ending processing.
[[NSNotificationCenter defaultCenter] postNotificationName:#"NotificationName" object:nil];
// Create an observer and hold a strong reference to it in a property
self.observer = [[TKLNotificationObserver alloc] init];
// During the manual calling of the same method the observer will not be dealloced, because ARC still
// holds a strong reference to the message reciever.
[self.observer notificationRecieved:nil];
return YES;
}
#end
TKLNotificationObserver.m:
#import "TKLNotificationObserver.h"
#import "TKLAppDelegate.h"
#implementation TKLNotificationObserver
- (id)init {
if (self = [super init]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(notificationRecieved:) name:#"NotificationName" object:nil];
}
return self;
}
- (void)notificationRecieved:(NSNotification *)notification {
[self doRemoveTheOnlyStrongReferenceOfThisObserver];
NSLog(#"returing from notification Observer");
}
- (void)doRemoveTheOnlyStrongReferenceOfThisObserver {
TKLAppDelegate * delegate = [[UIApplication sharedApplication] delegate];
delegate.observer = nil;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"NotificationName" object:nil];
NSLog(#"dealloc was called");
}
#end
Using the App Delegate in this way is no good style and only done for demonstration purposes, the real code does not involve the app delegate.
The output is:
dealloc was called
returing from notification Observer
returing from notification Observer
dealloc was called
That is in the first case dealloc is called before the notification processing finished. In the second case it behaves as I expected.
If I keep a strong reference to self inside notificationReceived the dealloc only happens after the processing. My expectation was, that ARC, the runtime or whoever else keeps this strong reference for me.
What is wrong with my code?
Or is something wrong with my expectation?
Is there any Apple- or Clang-provided documentation on this?
My expectation was, that ARC, the runtime or whoever else keeps this
strong reference for me.
That is not the case, as documented in the Clang/ARC documentation:
The self parameter variable of an Objective-C method is never actually
retained by the implementation. It is undefined behavior, or at least
dangerous, to cause an object to be deallocated during a message send
to that object.
Therefore, if calling doRemoveTheOnlyStrongReferenceOfThisObserver
can have the side-effect of releasing self, you would have to use
an temporary strong reference to avoid deallocation:
- (void)notificationRecieved:(NSNotification *)notification {
typeof(self) myself = self;
[self doRemoveTheOnlyStrongReferenceOfThisObserver];
NSLog(#"returing from notification Observer");
}
A better solution would probably to avoid this side-effect.
the first dealloc probably happens as you set the observer property of the appDelegate twice and therefore the first instance is dealloced as soon as you set it the second time
Related
I have a basic question regarding removing observer.
I have a ViewController parent class which is inherited by 3 ViewController child classes.
eg. BookVC -> BookHotelVC, BookFlightVC, BookTrainVC
Here, I added an observer in the viewDidLoad of parent class (I do [super viewDidLoad] in child ViewControllers) which notifies a method written in parent class. My code-
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(BookingCompleted:) name:#"BookingCompleted" object:nil];
Now I want to remove the observer when I move away from any of the child ViewControllers, but I can't write [super dealloc] in dealloc of each child ViewController because ARC doesn't permit this.
How can I remove the observer which is set ? Because whenever I move to child ViewController, a new observer is added which causes weird things (like, calling that method twice/thrice... - invoking alert twice/thrice...).
Kindly suggest.
Removing the observers in dealloc is fine, do not call [super dealloc] (as you saw, with ARC enabled, the compiler won't let you), simply write:
- (void)dealloc {
[self removeYourObservers];
}
Just don't call super! In ARC it's not required (see http://clang.llvm.org/docs/AutomaticReferenceCounting.html#dealloc).
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
I'm writing an iOS game with a bunch of different types of enemies and items/drops. Specific ones need to trigger things on different events, so I'm experimenting with using NSNotificationCenter.
Everything works when listener is defined in a way that's retained. When I define it locally or add it to an NSMutableArray, it's lost and the postNotification throws a EXC_BAD_ACCESS
This breaks, because the listener isn't retained past this.
MyListener *listener = [[MyListener alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:listener selector:#selector(myEventHandler:) name:#"MyEvent" object:nil];
This is a super basic example of what works:
MyListener *listener;
-(id)init {
listener = [[MyListener alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:listener selector:#selector(myEventHandler:) name:#"MyEvent" object:nil];
}
The issue is that I will have a bunch of different enemy/item classes that need to listen for an event. I don't want a different class-level variable for every single one - but admit that I may be going about this the wrong way. I'm still somewhat new to iOS.
Well, first of all, your init snippet is entirely wrong. init methods should look more like this:
- (instancetype) {
self = [super init];
if (self) {
// initialize
}
return self;
}
And in your example, // initialize would be replaced with:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(myEventHandler:)
name:#"MyEvent"
object:nil];
But what's most important here is that at some point before this object is completely deallocated, we must stop observing. If we do not, after this object is deallocated, NSNotificationCenter will try to send a message to a deallocated object, which causes your EXC_BAD_ACCESS.
You may wish to stop observing earlier than dealloc, but at a minimum, you need to add this to your class:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
As for keeping the object alive, well that's as simple as keeping a strong reference to it. This is sort of an entirely different question. Although... if you're trying to keep an object alive simply to respond to a notification, there's no need to even use an object here.
You can give the notification center a block to respond to notification with using the following method:
- (id)addObserverForName:(NSString *)name
object:(id)obj
queue:(NSOperationQueue *)queue
usingBlock:(void (^)(NSNotification *))block
I'm trying to create a class cluster as subclass of UIViewController to accomplish some points:
1. Different behavior of the ViewController depending on actual iOS version
2. iOS version checks don't clutter up the code
3. Caller doesn't need to care
So far I got the classes MyViewController, MyViewController_iOS7 and MyViewController_Legacy.
To create instances I call the method myViewControllerWithStuff:(StuffClass*)stuff which is implemented like:
+(id)myViewControllerWithStuff:(StuffClass*)stuff
{
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1)
{
return [[MyViewController_iOS7 alloc] initWithStuff:stuff];
}
else
{
return [[MyViewController_Legacy alloc] initWithStuff:stuff];
}
}
The caller uses myViewControllerWithStuff:. After that the so created view controller gets pushed onto a UINavigationController's navigation stack.
This nearly works as intended with one big downside: ARC doesn't dealloc the instance of MyViewController_xxx when it gets popped from the navigation stack. Doesn't matter which iOS version.
What am I missing?
UPDATE: -initWithStuff:
-(id)initWithStuff:(StuffClass*)stuff
{
if (self = [super init])
{
self.stuff = stuff;
}
return self;
}
This method is also implemented in MyViewController. The differences kick in later (e.g. viewDidLoad:).
First of all: Thanks for all your help, comments, answers, suggestions...
Of course there was another strong reference to the MyViewController-object. But it wasn't that obvious, because it was not a property or instance variable.
In viewDidLoad I did the following:
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillResignActiveNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
[self saveState];
}];
This should prevent data loss in case the user sends the app to the background. Of course the block captures the needed parts of its environment. In this case it captured self. The block keeps self alive until it (the block) gets destroyed, which is the case when e.g. [[NSNotificationCenter defaultCenter] removeObserver:self]; gets called. But, bad luck, this call is placed in the dealloc method of MyViewController which won't get called as long as the block exists...
The fix is as follows:
__weak MyViewController *weakSelf = self;
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillResignActiveNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
[weakSelf saveState];
}];
Now the block captures weakSelf. This way it can't keep the MyViewController-object alive and everything deallocs and works just fine.
I was trying to call an existing method of my ViewController.m from AppDelegate.m inside the applicationDidEnterBackground method, so I found this link: Calling UIViewController method from app delegate, which told me to implement this code:
In my ViewController.m
-(void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.myViewController = self;
}
In my AppDelegate:
#class MyViewController;
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (weak, nonatomic) MyViewController *myViewController;
#end
And in the AppDelegate's implementation:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[self.myViewController method];
}
So I put this code in my project and it worked fine, but I didn't understand how the code works, line by line. What does the sharedApplication do? Why must I set a delegate instead of just creating an instance of ViewController, like:
ViewController * instance = [[ViewController alloc] init];
[instance method];
Background information (class definition vs class instance)
The important concept here is the difference between a class definition and a class instance.
The class definition is the source code for the class. For example ViewController.m contains the definition for the myViewController class, and AppDelegate.m contains the definition for the AppDelegate class. The other class mentioned in your question is UIApplication. That is a system-defined class, i.e. you don't have the source code for that class.
A class instance is a chunk of memory on the heap, and a pointer to that memory. A class instance is typically created with a line of code like this
myClass *foo = [[myClass alloc] init];
Note that alloc reserves space on the heap for the class, and then init sets the initial values for the variables/properties of the class. A pointer to the instance is then stored in foo.
When your application starts, the following sequence of events occurs (roughly speaking):
the system creates an instance of the UIApplication class
the pointer to the UIApplication instance is stored somewhere in a
system variable
the system creates an instance of the AppDelegate class
the pointer to the AppDelegate is stored in a variable called
delegate in the UIApplication instance
the system creates an instance of the MyViewController class
the pointer to the MyViewController class is stored somewhere
The storage of the pointer to MyViewController is where things get messy. The AppDelegate class has a UIWindow property called window. (You can see that in AppDelegate.h.) If the app only has one view controller, then the pointer to that view controller is stored in the window.rootViewController property. But if the app has multiple view controllers (under a UINavigationController or a UITabBarController) then things get complicated.
The spaghetti code solution
So the issue that you face is this: when the system calls the applicationDidEnterBackground method, how do you get the pointer to the view controller? Well, technically, the app delegate has a pointer to the view controller somewhere under the window property, but there's no easy way to get that pointer (assuming the app has more than one view controller).
The other thread suggested a spaghetti code approach to the problem. (Note that the spaghetti code approach was suggested only because the OP in that other thread didn't want to do things correctly with notifications.) Here's how the spaghetti code works
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.myViewController = self;
This code retrieves the pointer to the UIApplication instance that the system created, and then queries the delegate property to get a pointer to the AppDelegate instance. The pointer to self, which is a pointer to the MyViewController instance, is then stored in a property in the AppDelegate.
The pointer to the MyViewController instance can then be used when the system calls applicationDidEnterBackground.
The correct solution
The correct solution is to use notifications (as in kkumpavat's answer)
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
}
- (void)didEnterBackground
{
NSLog( #"Entering background now" );
}
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
With notifications, you aren't storing redundant pointers to your view controllers, and you don't have to figure out where the system has stored the pointer to your view controller. By calling addObserver for the UIApplicationDidEnterBackgroundNotification you're telling the system to call the view controller's didEnterBackground method directly.
You have two question here.
1) What does the sharedApplication do?
The [UIApplication sharedApplication] gives you UIApplication instance belongs to your application. This is centralised point of control for you App. For more information you can read UIApplication class reference on iOS developer site.
2) Why must I set a delegate instead of just creating an instance of ViewController?
Creating controller in AppDelegate again using alloc/init will create new instance and this new instance does not point to the controller you are referring to. So you will not get result you are looking for.
However in this particular use case of applicationDidEnterBackground, you don't need to have reference of you controller in AppDelegate. You ViewController can register for UIApplicationDidEnterBackgroundNotification notification in viewDidLoad function and unregister in dealloc function.
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(yourMethod) name:UIApplicationDidEnterBackgroundNotification object:nil];
//Your implementation
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
The view controller is already instantiated as part of the NIB/storyboard process, so if your app delegate does its own alloc/init, you are simply creating another instance (which bears no relation to the one created the NIB/storyboard).
The purpose of the construct you outline is merely to give the app delegate a reference to the view controller that the NIB/storyboard instantiated for you.
Context
We were developing an ios app that can uses opencv and had to change our viewcontrollers to .mm
opencv related functions in the .mm won't execute code that involves changes in the ui.
GazeTracker is an NSObject that tells the state of the user's gaze and it works fine
we thought of using observers so that we'll use a selector in the viewController called stateChanged which will execute whenever the state in gazeTracker is changed.
"stateChanged" is never called. We initially thought it was just gazeTracker so we replaced it with "self" (meaning the viewController) and it still won't work.
Our understanding of the "observer" is that when a value in an object is changed, the selector is called. However we don't know the purpose of "object" in "addObserver:selector:name:object".
the original code
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:gazeTracker.state
selector:#selector(stateChanged)
name:#"stateChanged"
object:nil];
}
-(void)stateChanged{
NSLog(#"some value in gaze tracker has changed");
}
with "self"
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(stateChanged)
name:#"stateChanged"
object:nil];
}
-(void)stateChanged{
NSLog(#"some value in gaze tracker has changed");
}