Objective C, Almost closures?

I’m about toe deep in ObjC and Cocoa and I’m starting to get that warm fuzzy feeling everytime I message and object without needing a type cast. I get really warm/fuzzy when I use @selector() to throw extra executable logic from a long running process back onto the main thread. Now I’m thinking about the @selector idea and wondering how close it is to closures. I’d like to be able to define a method on an interface… *ahem* …protocol that takes a selector as a form of callback. Though Cocoa makes extensive use of delegates I don’t want to haff to set a delegate instance variable and define another protocol for something as simple as an inlined callback operation. In other words I wanna say: “Mr. Object, do dis stuff when your data becomes available.” Back into the manuals to learn about @selectors.

2 thoughts on “Objective C, Almost closures?

  1. True anonymous closures are probably a ways off, but possible in the future. A selector isn’t so much a closure as it is a function pointer that’s bound at runtime. Selectors aren’t good for closure or inner class type things, but there’s a bunch of infrastructure built around selectors and customizing how objects behave when they receive selectors that aren’t in their implementation.
    It’s really complicated, but take a look at the object an instance of OCMockObject returns when you send it “stub” or “expect,” particularly what it does with forwardInvocation:. This is an example of trampolining– you call a method on an object, and that object returns a magical proxy object that exists just to collect an invocation and bounce it back to the first object. This is also how NSUndoManager resgisters undoable events.
    You should also look at NSInvocation.

  2. I think I get the jest on selectors now. They are a distinct type that represent a function pointer that requires the instance to be invoked. They also have no access to local vars the way a closure would. I just had to hit the books a little harder to figure it out. Thanx again Jamie!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s