Should I prefer NSNotificactionCenter or .NET events when using Monotouch? - events

When developing in Monotouch, is it "better" to us real .NET events or NSNotificationCenter?
Simple example: I have a UIViewController. It offers an event "CallbackWhenDisappeared". This event is triggred in ViewDidDisappear. Who ever is interested can register to the event.
I could as well post a "MyFancyControllerHasDisappeared" on the NSNotificationCenter and let interested objects subscribe there.
Which version is to be preferred?
The disadvantage with the .NET events I see: the disappearing controller might hold a reference to the subscribing controller (or the other way round?) and might not be garbage collected.
I also like the loose coupling when using NSNotificationCenter compared to the events where the classes really have to know each other.
Is there a wrong or a right way of doing it?

I actually prefer to use TinyMessenger. Unlike NSNotifications it handles the asynchronicity of the calls for you as part of the framework.
Managed objects also allow for better debuggability especially considering that these are usually cross container calls I find this to be very very useful.
var messageHub = new TinyMessengerHub();
// Publishing a message is as simple as calling the "Publish" method.
messageHub.Publish(new MyMessage());
// We can also publish asyncronously if necessary
messageHub.PublishAsync(new MyMessage());
// And we can get a callback when publishing is completed
messageHub.PublishAsync(new MyMessage(), MyCallback);
// MyCallback is executed on completion
https://github.com/grumpydev/TinyMessenger

There is no really right or wrong, but in my opinion it looks so:
NotificationCenter - You don't know which Objects are interested on the "Events", you send it out and any object can receive it
.Net Events - If there is a direct connection between two objects use this, for example like an UIViewController shows an other UIViewcontroller as Modal. The ModalUIViewcontroller fires an event, if it will hide and the UIViewController is Suscribed to it

Related

Use PropertyChanged or WeakSubscribe?

What is the best way to track a property change?
I have the following concerns why I can't make a decision.
- PropertyChanged can prevent garbage collection from collecting a ViewModel that uses its own PropertyChanged event?
- Could WeakSubscribe be gone at any moment in time when using to track ViewModels own property changes?
Did anyone test this or just know the answer ?
In general, you won't hit problems if you use PropertyChanged strong subscriptions.... However, there are some cases where this can lead to "leaks" - e.g. if you subscribe on a sub-object which has a longer lifetime than a "normal" ViewModel (e.g. a singleton service).
To be safe, though, you can use WeakSubscribe - as long as you store a reference to the returned token from the WeakSubscribe call in a member field in your view, then this will ensure that the subscription remains active for at least as long as your View is in memory.
Regardless of strong or weak, one additional thing to aim for ... is to try to release the event subscription (either strong or weak) as early as you can. This will help prevent event callbacks being fired after the View has disappeared.

What is *like* a promise but can resolve mutliple times?

I am looking for a pub/sub mechanism that behaves like a promise but can resolve multiple times, and behaves like an event except if you subscribe after a notification has happened it triggers with the most recent value.
I am aware of notify, but deferred.notify is order-sensitive, so in that way it behaves just like an event. eg:
d.notify('notify before'); // Not observed :(
d.promise.progress(function(data){ console.log(data) });
d.notify('notify after'); // Observed
setTimeout(function(){ d.notify('notify much later') }, 100); // Also Observed
fiddle: http://jsfiddle.net/foLhag3b/
The notification system I'd like is a good fit for a UI component that should update to reflect the state of the data behind it. In these cases, you don't want to care about whether the data has arrived yet or not, and you want updates when they come in.
Maybe this is similar to Immediate mode UIs, but is distinct because it is message based.
The state of the art for message based UI updating, as far as I'm aware, is something which uses a promise or callback to initialize, then also binds an update event:
myUIComponent.gotData(model.data);
model.onUpdate(myUIComponent.gotData); // doing two things is 2x teh workz :(
I don't want to have to do both. I don't think anyone should have to, the use case is common enough to abstract.
model.whenever(myUIComponent.gotData); // yay one intention === one line of code
I could build a mechanism to do what I want, but I wanted to see if a pub/sub mechanism like this already exists. A lot of smart people have done a lot in CS and I figure this concept must exist, I just am looking for the name of it.
To be clear, I'm not looking to change an entire framework, say to Angular or React. I'm looking only for a pub/sub mechanism. Preferably an implementation of a known concept with a snazzy name like notifr or lemme-kno or touch-base.
You'll want to have a look at (functional) reactive programming. The concept you are looking for is known as a Behavior or Signal in FRP. It models the change of a value over time, and can be inspected at any time (continuously holds a value, in contrast to a stream that discretely fires events).
var ui = state.map(render); // whenever state updates, so does ui with render() result
Some popular libraries in JS are Bacon and Rx, which use their own terminology however: you'll find properties and observables.

Is ok to duplicate NSURLsession delegate classes iOS

I have multiple classes that use NSURLSession, and they may run at the same time, is OK if I make them all NSURLSession delegates?
Code:
First delegate:
#interface userLoginScreen : UIViewController <UIAlertViewDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDownloadDelegate>
Second delegate:
#interface syncDataOperation : NSOperation <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDownloadDelegate>
Is it a good practice to do this?
All you're doing in your example there is saying "all these classes implement this interface", which is perfectly fine, and has no real bearing on what actually happens at runtime.
What I think you're getting at is those scenarios where you may want to have a single delegate object receiving delegate messages from multiple objects in an NSURLSession. For example, it's perfectly normal to have a single delegate handle callbacks for multiple NSURLSessionTask objects.
The only real problem might be if you were to have the delegate messages coming in on multiple different threads/queues. However, Apple have designed for that; when you create an NSURLSession object you can provide a specific delegateQueue for the callbacks to be sent on. This is the delegateQueue in sessionWithConfiguration:delegate:delegateQueue, for example.
If you don't provide one, NSURLSession "creates a serial NSOperationQueue object on which to perform all delegate method calls and completion handler calls", which is a very sensible default.
Tasks that you create under one NSURLSession will use that delegate queue for their delegate messages, too.
For example, if you create an NSURLSession without specifying a delegateQueue, it will create a serial queue for its delegate messages. If you then call downloadTaskWithRequest on it to create a NSURLSessionDownloadTask, the download task's delegate methods will use the same queue.
If you create thirty NSURLSessionDownloadTasks on it, all pointing at the same delegate, they'll all use the same queue to send their delegate messages, and because it's a serial queue, your delegate won't ever have two delegate messages arrive simultaneously, so you don't have to worry about coding to cope with that situation. (And all the delegate messages pass pointers to the related NSURLSession/NSURLSessionTask so you can tell which messages came from which tasks.)
Normally all the delegate objects you have to deal with a particular set of tasks will be dealing with tasks created underneath the same NSURLSession object, so everything uses the same delegate queue by default, and if you don't bother passing in a delegateQueue, NSURLSession, as I've said, provides a sensible one for you, so mostly the delegate stuff should Just Work.

Coordination between classes in Cocoa

I have a program with a lot of controllers which need to co - ordinate with each other . I'm confused about which mechanism to use . What are the pro and con of using :
Delegate
Bindings
Notifications
Key Value observing
Specifically is there any problem with using notifications all over place ? I'm planning to do that as it allows a class to just put out some information and not bother about anything else.
Use delegates if you want your object to have knowledge of specific methods to call when it needs to inform an observer of a state change. Notifications are more appropriate when you have multiple observers. Both of these require manual intervention, i.e. you need to explicitly call the delegate methods or post notifications when state changes.
Bindings and KVO work hand-in-hand, and are automatic ways to update state in one object (e.g. UI) when state in another object changes.

Cocoa Controllers - best practice for notifying on completion, for disposal?

I have an ObjC controller object.
After alloc/init of the object, I get it to do a job asynchronously:
[myObject doSomeThingsOverTime];
The method sets things in motion, and then returns immediately.
Question: what is the best way to be notified of the result in the future, so that I can release myObject and react to the work having been completed? Should I observe/post notifications? Or supply the object with a method to callback? Or other?
I'm personally a fan of the notification center route. It allows for more than one observer (may or may not be relevant to you).
The delegate route is also valid, and is used quite frequently in the frameworks.
I think it comes down to personal preference. If it's your own code, you should go for what's most readable and simple for your particular situation. I don't think one is more or less valid than the other.
Have you looked at the NSOperation and NSOperationQueue classes? You can observe the isFinished of an NSOperation object so you will get notified when it is completed.

Resources