views:

86

answers:

1

Is that possible?

+5  A: 

Here's an example of how you would accomplish such a task:

#import <Foundation/Foundation.h>
typedef int (^IntBlock)();



@interface myobj : NSObject
{
    IntBlock compare;
}

@property(readwrite, copy) IntBlock compare;

@end

@implementation myobj

@synthesize compare;

@end
long dbltolongbits(double value)
{
    return *(((long*) &value));
}

int main () {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    myobj *ob = [[myobj alloc] init];
    ob.compare = ^
    {
        return rand();
    };
    NSLog(@"%i", ob.compare());
    [ob release];
    [pool drain];
    return 0;
}

Now, the only thing that would need to change if you needed to change the type of compare would be the typedef int (^IntBlock)(). If you need to pass two objects to it, change it to this: typedef int (^IntBlock)(id, id), and change you block to:

^ (id obj1, id obj2)
{
    return rand();
};

I hope this helps.

Richard J. Ross III
the block should be a copy property, not assign. Blocks are objects.
Joshua Weinberg
Oh? I thought they were a special C-struct from the article here: http://thirdcog.eu/pwcblocks/
Richard J. Ross III
Blocks are objects? Cool! I thought they were a special C-struct too.
gurghet
Blocks are most certainly objects in the Obj-C runtime. You need to copy them off the stack using Block_copy or [block copy] to make them actually survive the stack frame.
Joshua Weinberg
Oh yep, read the article and thats what they are doing, just not in objective-c code :) Make sure that you have an autorelease pool in place though...
Richard J. Ross III
You can only with an approriate runtime with the correct symbols. In Objective-C you're using Apple's block runtime, which makes them objects. In the 'standard' you'd still need to copy/release them using the C functions Block_copy/Block_release. Which map to [block copy], [block release] in Obj-C
Joshua Weinberg
@Richard: I'd recommend reading the full blocks spec, its only a couple of pages long and will go over how blocks work in C, C++ and Obj-C. Like in Obj-C blocks will retain objects that are in their scope, in C++ it behaves differently and I believe it actually creates a new object with the copy constructor, except when objects are perpended with __block...So yea, read the spec.
Joshua Weinberg