Coming from a Ruby background, I try to understand and pick the
best from Obj-C/Cococa and learn how to use brilliant ideas to
improve my coding.
Tonight I was working on a simple demo app to learn how things are
done in the Obj-C world and see how they would transpose to the
MacRuby world.
Everything went well until the KVO question came along.
Let's say I have a controller that we are going to call Brain.
We also have a lot of simpler objects that don't do anything but
having a state and being displayed, we are going to call them Task
instances. The brain is called every X seconds to "think".
My understanding is that an Obj-C developer would register all the
tasks instance with the brain using a KVO and the brain would send
notifications when it's being called to "think". So, every time a
new task is being created, an observer is added on the brain with
the new task key. Each Task instance has an
observeValueForKeyPath:ofObject:change:context: method implemented
which checks that the notification is meant for itself and if it is,
to act accordingly.
While the concept is simple and attractive. I wonder if it wouldn't
be simpler to forget about kvo's and simply keep the list of
registered tasks in the brain and the brain would call the tasks
directly and tell them to change.
It sounds to me that in the MacRuby world, it would be more
efficient. If we have 250 tasks for instance, when a notification is
being sent, every single task in the 250 tasks created, will receive
the notification and will check what to do with it. If we had a
simple hash/dictionary in the brain, we could directly find the task
to handle and call it directly without having to go through the 250.
Am I missing something or in this specific case and because we use
Ruby, KVO aren't the way to go?
KVO isn’t really the right hammer for your nail, but I’m not sure I
understand your scenario properly.
You have a Brain which every «interval» picks a task to work on and
does some work.
KVO is about observing changes in a key’s value and doing something
with it. It’s an inter-object dependency mechanism. A common way to
use it is to update some UI when the value of a model object’s key
changes. An example:
You have a table view which shows the current state of all your tasks.
Each task is just a countdown from 10 to 0, and you want the table to
display what stage in the countdown each object is at. Your controller
observes all the tasks, and when a task changes it tells the
appropriate row in the table to refresh.
In your case, the Brain has nothing the tasks are interested in
observing. “I’m doing some work” doesn’t make sense from an OO point
of view since the Brain should be doing the work and not the Task.
Hope that helps,
-Ben
_______________________________________________
MacRuby-devel mailing list
MacRuby-devel@lists.macosforge.org
http://lists.macosforge.org/mailman/listinfo.cgi/macruby-devel