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
2010-10-14 17:09:29
the block should be a copy property, not assign. Blocks are objects.
Joshua Weinberg
2010-10-14 17:12:46
Oh? I thought they were a special C-struct from the article here: http://thirdcog.eu/pwcblocks/
Richard J. Ross III
2010-10-14 17:16:20
Blocks are objects? Cool! I thought they were a special C-struct too.
gurghet
2010-10-14 17:17:08
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
2010-10-14 17:17:47
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
2010-10-14 17:19:33
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
2010-10-14 17:19:44
@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
2010-10-14 17:24:20