Blog

Blocks in Objective-C

There have been quite a lot of news about blocks in C recently. What I wonder however is: will there be a Objective-C block object that wraps such a new C block?

Thing is: You can’t send messages to C-Blocks, they’re just as primitiv as an int, or a float, even if they’re more complex. In Obj-C you also have string literals like @”a string”, which you can send messages to. Why not also have literal blocks like @[:arg | arg doSomething]? I think that would really make live a bit easier sometimes.

@[:arg | arg doSomething] might look a bit too smalltalkish for some people, but on the other hand the selectors in Obj-C also look just as cool as in Smalltalk.

Anyway, looking forward to seeing blocks in Cocoa.

Karsten

Comments

Anon — September 2nd, 2008 at 19:49

If you want your suggestions to be heard, send them to cfe-dev@cs.uiuc.edu (the clang mailing list) instead of posting them on your blog 😛

rastap — September 2nd, 2008 at 22:24

Isn’t NSInvocation what you are looking for?

Johannes Fortmann — September 2nd, 2008 at 22:36

I already posted this on http://lists.cs.uiuc.edu/pipermail/cfe-dev/2008-September/002700.html Basically, blocks are provisioned to be objective-c objects, but for some strange reason the first pointer doesn’t point to an isa, it points to an object (*). The comments in the source as well as the test case say otherwise, yet this can’t be a simple oversight. I sure hope they change that; having blocks as native objects (however limited) would be soo cool.

(*) With: struct Block_impl { Class isa; char private_stuff[]; }; it should be something like: struct Block { Block_impl impl; char private_stuff[]; } but it is struct Block { Block_impl *impl; char private_stuff[]; }

Karsten — September 3rd, 2008 at 6:45

rastap: no, NSInvocation is different. it’s like a prepared message send, that you can evaluate with some arguments. However, the method that you call has to exist. NSInvocation is more a bit like function pointers in C. Blocks are much more dynamic. NSInvocations are also a bit hard to setup in standard Cocoa.

Johanne: interesting…that indeed seems a bit weird. However, if they write some sort of wrapper class for the c-blocks, this should be just fine i think. But then it couldn’t be bridged to Carbon as easily as NSStrings. I guess time will tell what they come up with.

Karsten

Anonymous — September 14th, 2008 at 19:39

Yes, there will be blocks in Snow Leopard. Yes they will be completely different from anything already in Cocoa. They will have new syntax along the lines of:

^{/*block definition*/}