AVFoundation IOS: playing Background Music [duplicate] - ios

i have an NSNotificationCenter selector,
where to put it ? in the delegate (if yes then where?) in the controller?
where to put the method as well.
do i need to dealloc the NSNotificationCenter ?
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(deviceNotificationReceived:) name:UIApplicationDidBecomeActiveNotification object:nil];
- (void)deviceNotificationReceived:(NSNotification *)notification
{
[self.soundMgr endInterruption];
}

The deviceNotificationReceived: method must be an instance method of the argument to addObserver:. It is self in this instance, so your method should go in the same class.
You should not release the NotificationCenter, as you did not create or retain it.
Your question was a little hard to understand, is this what you were asking?

Hi, i have an NSNotificationCenter selector,
okay, you mean you have a selector for a method in NSNotificationCenter.
In Objective-C, “selector” has two
meanings. It can be used to refer
simply to the name of a method when
it’s used in a source-code message to
an object. It also, though, refers to
the unique identifier that replaces
the name when the source code is
compiled.
http://developer.apple.com/mac/library/documentation/cocoa/....../ocSelectors.html
So you have created a selector that refer to a method.
where to put it ?
It's a variable, you can store it where ever you feel it fits in your design.
in the delegate
See above.
(if yes then where?)
It's a variable, it depends on your usage.
in the controller?
Do you have controller? Depends on your design.
where to put the method as well.
Which method?
do i need to dealloc the NSNotificationCenter ?
No, [NSNotificationCenter defaultCenter] returns a reference to the notification center, you don't dealloc it.

Since you are subscribing to the UIApplicationDidBecomeActiveNotification notification, the most logical place to put the notification is in the applicationdDidFinishLaunching method of your app delegate.
That's the first point your code gets called, so you cannot set it earlier.

where to put it ?
It depend on when you need to register for notification. One way is to add observer in 'init' method of the class and remove notification in 'dealloc'method of the class.

Related

Better way to pass userInfo data with NSNotificationCenter in iOS

[[NSNotificationCenter defaultCenter] postNotificationName:#"TapNewProduct" object:self.productID];
(or)
NSDictionary *dict = #{#"productID":self.productID};
[[NSNotificationCenter defaultCenter] postNotificationName:#"TapNewProduct" object:nil userInfo:dict];
Which is better method from above two?
Your first option abuses the 'sender' parameter of the notification because it's simple. It'll work, but it isn't correct. The idea with that parameter is that you can use it to filter the notifications that you receive. If you'll use it like that then fine, but it isn't for passing user info.
So, the second option is the correct one.
Imagine someone else coming to help on your project in the future - the more your code is written to follow standards the easier it'll be for them to help you.
In both the methods you are gonna get same output. you will fetch the object by notification.object.
but in this,
[[NSNotificationCenter defaultCenter] postNotificationName:#"TapNewProduct" object:self.productID];
there is no need to create a dictionary. it can reduce the code.
The object parameter is the "notificationSender", that is, the object posting the notification. The userInfo parameter is intended to contain information about the the notification and it may be nil.
More details in Apple's reference documentation.
postNotificationName:object: method invokes postNotificationName:object:userInfo: with a userInfo argument of nil.So basically there is no reason to argue with which one is better than the other.

NSNotificationCenter - removing observer when observed objected is deallocated

I use the following line to add an observer:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(itemDidFinishPlaying) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
My observer (self) will never be deallocated.
But when the user starts playing a different item, the old self.playerItem will be deallocated---but will always be replaced with a new one, which I want to continue observing.
When that happens, what happens in regards to my observer's status as an observer? Do I need to do something to stop observing the deallocated object, as is required with KVO? Or will I continue observing the new object at self.playerItem? Or will my observer automatically be "unregistered?"
If I need to remove the observer, I wonder why there's no corresponding removeObserver method that enables one to specify a selector; it seems I can remove an observer only wholesale via removeObserver:(id)notificationObserver.
According to the NSNotificationCenter class reference:
Be sure to invoke removeObserver: or removeObserver:name:object:
before notificationObserver or any object specified in
addObserver:selector:name:object: is deallocated.
So: you should unregister your observer before self.playerItem deallocated.
But when the user starts playing a different item, the old
self.playerItem will be deallocated---but will always be replaced with
a new one, which I want to continue observing.
You may pass nil as the last parameter of addObserver:selector:name:object: method:
Adds an entry to the receiver’s dispatch table with an observer, a notification selector and optional criteria: notification name and sender.
If you don't specify
If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.
So you will receive notification AVPlayerItemDidPlayToEndTimeNotification from any object that posts it.
Since iOS 9 it is no longer needed to remove an observer from an object:
In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated.
However, block based observers need to be un-registered as before:
Block based observers via the -[NSNotificationCenter addObserverForName:object:queue:usingBlock] method still need to be un-registered when no longer in use since the system still holds a strong reference to these observers.
More information can be found here:
https://developer.apple.com/library/content/releasenotes/Foundation/RN-FoundationOlderNotes/index.html#10_11NotificationCenter

Last method to be called consistently in an iOS class?

In an iOS class that will not appear as a view e.g.
#interface MyDataClass : NSObject{}
Is there a method that can be overridden and is consistently called at the end of the classes' execution/lifecycle similar to viewDidUnload or dealloc, that can call methods safely?
Alternatively how would one go about implementing a method that could recognise the completion of the useful lifespan of such a class?
I believe dealloc is the last method that's get called if an NSObject subclass is released from memory.
- (void)dealloc
{
[super dealloc];
}
like
- (void)dealloc
{
[super dealloc];
}
?
If you mean a method that runs at the end of lifetime of the Class as a whole (not an instance), I wonder how is the runtime supposed to know when you are done using a class (you can create new instances at any time)? There is an +initialize method, but technically the class itself is available forever (until the program exits).
If you mean the lifetime of an instance, the method you are looking for is -dealloc.
-dealloc is called whenever an object's internal reference count reaches zero. In non-ARC code, if you override it you must call the superclass' implementation, so that ultimately NSObject's -dealloc is called and that is when the memory is freed.
EDIT: Regarding low memory situations, this is how you register for notifications:
// Somewhere inside the -init method of your class
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(myMethod:)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
Inside dealloc, you MUST do this:
[[NSNotificationCenter defaultCenter] removeObserver:self];
...otherwise, your app may crash.
And of course, you must implement a method with the following signature that will be called on low-memory situations:
- (void) myMethod:(NSNotification*) notification
{
// Do some cleanup here, perhaps.
}
(otherwise, your app will crash)
Let's imagine you want to have a different method, other than dealloc, called on low memory conditions (not when the object is deallocated). Which object would call that method?
viewDidUnload is part of the UI Framework and it is called by it. When the application gets a message about low memory conditions, the framework just redirects the message to all active view controllers.
You can implement the same by creating a method on your custom class, e.g. -(void)onLowMemory and then call it from you application delegate from applicationDidReceiveMemoryWarning method or you can register the class to listen to UIApplicationDidReceiveMemoryWarningNotification.
This stackoverflow link more or less answers my question, but not entirely. I think my question has more to do with architecture or method procurement and procedure as opposed to something that can be answered simply.

Removing all notification observer from a single place

I want to remove a notification observer and I am using the method:
[[NSNotificationCenter defaultCenter] removeObserver: name:#"myNotification" object:nil];
for this. Now there are many observers who are listening to this notification and I want to remove all of them in one shot from a centralised place. Can I pass 'nil' in first parameter and it will remove all observers who are listening to myNotification?
You can remove an object from the notification center all together which means no notifications will get triggered. For example, when I have a view controller that has registered for notifications, I include this line in my dealloc.
[[NSNotificationCenter defaultCenter] removeObserver:self];
This is at the object level...so it will unregister for many notifications. It won't unregister for one notification in many objects.
Hope I understood your question correctly.
In case of Swift, you doing it like this:
NSNotificationCenter.defaultCenter().removeObserver(self)
And in Swift 3:
NotificationCenter.default.removeObserver(self)
Unfortunately, there is no way to remove all observers of a specific notification in one place. While there are certainly cases where this would be nice, it would be a dangerous thing to do as generally, the object doing the observing should be responsible for adding and removing itself as an observer of a particular notification. This ensures no unpredictable behavior b/c observers can come and go so they configure and clean up after themselves.
If an object that generates notifications goes away, it won't matter to the observer as the observer doesn't know about that object anyway. It just means that object won't be generating any more notifications.
[EDIT: RESPONSE TO YOUR COMMENT RE CLASS B STOPPING CLASS A FROM OBSERVING]
I just saw your comment. There are different ways to accomplish this, particularly if class B knows about class A. As you reference classes it sounds like you want to affect all instances of a class vs a particular instance. If you have some condition you can check when handling the notification, that's how I would approach this. In the notification handler something like:
if ([self shouldRespondToNotificationNamed:notification.name]) {
[self performNotificationAction];
}
If you don't have a condition you can check, then create one either in the class in question as an iVar or in a place where you can access it globally for all class instances. I generally use a singleton to store global app state that doesn't persist. If it persists, then use whatever method you're using for other state.

Where and how do I register an object for receiving a Notification?

For example, when memory gets low, the System sends a UIApplicationDidReceiveMemoryWarningNotification notification. That's all Apple says in its docs at that point. But where does this notification come from, and to which method is it sent? Or where and how do I register what that I get notified?
From within the initialization code of the class you wish to receive the notification make the following method call:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleMemoryWarning:) name: UIApplicationDidReceiveMemoryWarningNotification object:nil];
This assumes that your class also implements a handleMemoryWarning method as follows:
- (void) handleMemoryWarning:(NSNotification *)notification
{
}
Much simpler to use the application delegate and implement the optional method
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
Most common notifications are also available translated into calls to a delegate, typically to optional methods in a formal protocol. Your delegate can be whatever object you like.
It is sent to the notification center, where all notifications are centralized. An object that wants to get informed about this notification registers itself to the notification center by telling which notification it wants to get informed and which method should be invoqued when the notification is raised.
For more information you can take a look to Notification programming topics for Cocoa and NSNotification class reference .
Be warned that your selector will need to take the notification as an argument.
If you use something like #selector(handleMemoryWarning) and - (void) handleMemoryWarning { } the object WILL NOT send the notification and you'll still be holding onto all of your memory.
I was just bitten by this.

Resources