可以创建“块”的类别,对象在Objective-C [英] Is it possible to create a category of the "Block" object in Objective-C
问题描述
我想为Objective-C块创建一个类别来添加函数。
I would like to add functions by creating a category for Objective-C Blocks.
__block int (^aBlock)(int) = ^int( int n ){
if( n <= 1 ) return n;
return aBlock( n - 1 ) + aBlock( n - 2 );
};
而不是只允许正常的 [aBlock copy]
, [aBlock retain]
, [aBlock release]
, / code>。我可以做类似的事情:
Instead of just allowing the normal [aBlock copy]
, [aBlock retain]
, [aBlock release]
, [aBlock autorelease]
. I could do thing like:
[aBlock mapTo:anArray];
可能的类别
@interface UnknownBlockClass (map)
- (NSArray *)mapTo:(NSArray *)array_;
@end
推荐答案
pwc是正确的,因为你不能为你看不到的类创建类别。
@pwc is correct in that you can't create a category for a class that you can't see.
但是...
- 一些运行时内省揭示了一些有趣的信息。有许多类包含单词Block。其中一些看起来很有前景:
__ NSStackBlock
,__ NSMallocBlock
,__ NSAutoBlock
和NSBlock
。 - 一些更自省显示有希望的类继承自
NSBlock
- Some runtime introspection reveals some interesting information. There are a number of classes that contain the word "Block". Some of them look promising:
__NSStackBlock
,__NSMallocBlock
,__NSAutoBlock
, andNSBlock
. - Some more introspection shows that the promising classes inherit from
NSBlock
所以看起来任何块都会是 NSBlock
。
So it looks like any block is going to be some instance or subclass of NSBlock
.
您可以在对象上创建方法,如下所示:
You can create a method on an object, like so:
@implementation Foo
- (void) doFoo {
//do something awesome with self, a block
//however, you can't do "self()".
//You'll have to cast it to a block-type variable and use that
}
@end
然后在运行时,可以将该方法移动到 NSBlock
类:
Then at runtime, you can move that method to the NSBlock
class:
Method m = class_getInstanceMethod([Foo class], @selector(doFoo));
IMP doFoo = method_getImplementation(m);
const char *type = method_getTypeEncoding(m);
Class nsblock = NSClassFromString(@"NSBlock");
class_addMethod(nsblock, @selector(doFoo), doFoo, type);
之后,块应该响应 doFoo
消息。
After this, blocks should respond to the doFoo
message.
这篇关于可以创建“块”的类别,对象在Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!