简体   繁体   English

Objective-C块语法

[英]Objective-C Block Syntax

Obj-C blocks are something I'm just using for the first time recently. Obj-C块是我刚刚第一次使用的东西。 I'm trying to understand the following block syntax: 我试图理解以下块语法:

In the header file: 在头文件中:

@property (nonatomic, copy) void (^completionBlock)(id obj, NSError *err);

In the main file: 在主文件中:

-(void)something{

id rootObject = nil;

// do something so rootObject is hopefully not nil

    if([self completionBlock])
        [self completionBlock](rootObject, nil); // What is this syntax referred to as?
}

I appreciate the assistance! 我很感激你的帮助!

Blocks are Objects. 块是对象。

In your case inside the method you are checking if the block is not nil and then you are calling it passing the two required arguments ... 在你的情况下你在方法中检查块是不是nil然后你正在调用它传递两个必需的参数...

Keep in mind that blocks are called in the same way ac function is ... 请记住,以与ac功能相同的方式调用块...

Below i have split the statement in two to let you understand better : 下面我将声明分成两部分让你更好地理解:

[self completionBlock]  //The property getter is called to retrieve the block object
   (rootObject, nil);   //The two required arguments are passed to the block object calling it

Its a block property, you can set a block at runtime. 它是一个块属性,您可以在运行时设置块。

Here is the syntax to set 这是要设置的语法

As it is void type, so within the class you can set a method by following code 由于它是void类型,因此在类中,您可以通过以下代码设置方法

self.completionBlock = ^(id aID, NSError *err){
    //do something here using id aID and NSError err
};

With following code you can call the method/block set previously. 使用以下代码,您可以调用先前设置的方法/块。

if([self completionBlock])//only a check to see if you have set it or not
{
        [self completionBlock](aID, nil);//calling
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM