Is it any loose coupling mechanism in Objective-C + Cocoa like C# delegates or C++Qt signals+slots?
For a large programs, the standard way to chalenge a complexity is to divide a program code into small objects. Most of the actual programming languages offer this functionality via classes, so is Objective-C. But after source code is separated into small object, the second challenge is to somehow connect them with each over. Standard approaches, supported by most languages are compositon (one object is a member field of another), inheritance, templates (generics) and callbacks. More cryptic techniques include method-level delagates (C#) and signals+slots (C++Qt). I like the delegates / signals idea, since while connecting two objects i can connect individual methods with each over, without objects knowing anything of each over. For C#, it will look like this:
var object1 = new CObject1();
var object2 = new CObject2();
object1.SomethingHappened += object2.HandleSomething;
In this code, is object1
calls it's SomethingHappened
delegate (like a normal method call) the HandleSomething
method of object2
will be called.
For C++Qt, it will look like this:
var object1 = new CObject1();
var object2 = new CObjec开发者_如何转开发t2();
connect( object1, SIGNAL(SomethingHappened()), object2, SLOT(HandleSomething()) );
The result will be exactly the same.
This technique has some advantages and disadvantages, but generally i like it more than interfaces since if program code base grows i can change connections and add new ones without creating tons of interfaces. After examination of Objective-C i havn't found any way to use this technique i like :(. It seems that Objective-C supports message passing perfectly well, but it requres for object1
to have a pointer to object2
in order to pass it a message. If some object needs to be connected to lots of other objects, in Objective-C i will be forced to give him pointers to each of the objects it must be connected.
So, the question :). Is it any approach in Objective-C programming that will closely resemble delegate / signal+slot types of connection, not a 'give first object an entire pointer to second object so it can pass a message to it'. Method-level connections are a bit more preferable to me than object-level connection ^_^.
I'll give you a couple of pointers to research:
- NSNotification
- Key Value Observing
- NSInvocation
- categories
The first two are the closest to what you are asking, but the latter two have a role in this general area.
精彩评论