【问题标题】:Declaring a method that takes a Block [duplicate]声明一个接受块的方法[重复]
【发布时间】:2013-08-11 19:50:34
【问题描述】:

我试图弄清楚如何声明一个将块作为参数并仅从外部范围记录整数值的方法。我看到的大多数示例都是在 indexesOfObjectsPassingTest: 等 Apple API 上执行此操作的,但我只想创建自己的简单版本。这是我所拥有的,目前无法正常工作:

@interface IAViewController ()
+(void)tell2:(void(^)(void)) thisBlock;
@end

...

NSInteger someInt=289456;
[IAViewController tell2:^{
    NSLog(@"what is this? %i", someInt);
}];

// ? how do I make this method signature work
+(void) tell2:(void (^thisBlock)) myInt{
    thisBlock(myInt);
}

如何使方法签名参数正常工作以输出 289456?

【问题讨论】:

  • 真的不认为这是一个骗子,这里不是在谈论 typedef
  • 它具有声明具有 Block 参数的方法的正确语法。
  • 谢谢@Fred,接受的答案非常有帮助!

标签: objective-c syntax objective-c-blocks


【解决方案1】:

当您将块类型声明为Objective-C 方法的参数时,块的标识符在类型之外。所以语法看起来像这样:

@interface IAViewController ()
+(void)tell2:(void(^)(void)) thisBlock;
@end

@implementation IAViewController
- (void)someMethod {
    NSInteger someInt=289456;
    [IAViewController tell2:^{
        NSLog(@"what is this? %i", someInt);
    }];
}

+(void) tell2:(void (^)(void))thisBlock {
    thisBlock();
}
@end

【讨论】:

  • 啊,好吧,所以第一个 void = 没有返回类型,第二个是没有参数,第三部分是传入的块。中间的 (^) 克拉是什么意思 - 或者它只是指定 this 的语法是一个块?
  • 你是对的,胡萝卜只是声明块的语法。在其他情况下(例如声明块变量),您可以将块名称放在胡萝卜旁边。这里有所不同,因为 Objective-C 方法总是看起来像 methodSignature:(<type>)<identifier>,所以你不包括块的标识符和它的类型。
【解决方案2】:

你的问题是你有文本 myInt 应该有块名称,然后你正在调用一个块,该块接受一个没有在任何地方声明的参数的 void 参数。

@interface 中的方法声明正确。在@implementation 中再次使用它并丢弃对myInt 的所有引用。

+(void)tell2:(void(^)(void)) thisBlock
{
    // your method implementation
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2011-02-25
    • 1970-01-01
    相关资源
    最近更新 更多