Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 我可以在一个位置传递一个命名函数吗;块;要求什么?_Objective C_Function_Anonymous Function_Named - Fatal编程技术网

Objective c 我可以在一个位置传递一个命名函数吗;块;要求什么?

Objective c 我可以在一个位置传递一个命名函数吗;块;要求什么?,objective-c,function,anonymous-function,named,Objective C,Function,Anonymous Function,Named,例如,打电话 little hat thing^(UIViewController*viewController,NSError*error)表示调用应具有匿名功能块: [lp setAuthenticateHandler:(^( UIViewController* vc, NSError *nsError ) { if( !nsError ) { puts( "GC auth success" ) ; } })]; 但是假设我希望在调用setAut

例如,打电话

little hat thing
^(UIViewController*viewController,NSError*error)
表示调用应具有匿名功能块:

[lp setAuthenticateHandler:(^( UIViewController* vc, NSError *nsError )
  {
    if( !nsError )
    {
      puts( "GC auth success" ) ;
    }
  })];

但是假设我希望在调用
setAuthenticateHandler
时使用的函数是命名的函数。我在其他地方见过使用选择器(functionName),但在这里似乎不起作用。

选择器和块是完全不同的概念

@选择器(functionName)
的类型为
SEL

是C级语法运行时特性,在Objective-C中,它实际上是一个对象

有关选择器的详细信息,请参见


有关块

的详细信息,块、选择器和函数指针(不确定后两者中的哪一个是命名函数)都是不兼容的类型,因此无法在需要另一种类型的参数时传递。幸运的是,如果您确实需要在基于块的API中使用函数指针或选择器,那么很容易做到这一点。块将捕获创建时在作用域中的函数指针和选择器,您可以在块中使用它们(就像它们处理任何其他变量一样)。例如,以下视图控制器向GCD(一种基于块的API)提供包装器,该包装器接受选择器或函数指针作为参数:

ViewController.h:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

当然,您可以显式调用任何方法或函数,并且接收器和参数都将被块捕获。

您需要提供一个块。没有什么能阻止你在块中调用你的名字。实际上,这个模式看起来像
\uuuyourClassName*weakSelf=self;[lp setAuthenticateHandler:(^(UIViewController*vc,NSError*NSError){if(!NSError){[weakSelf gcPlayerLoggedInSuccess];}
由于问题,您需要
\u-weak
ptr
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end
#import "ViewController.h"

void callback() { NSLog(@"call back function"); }

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self doSomethingWithCompletionSelector:@selector(callback)];
//    [self doSomethingWithCompletionFunction:callback];

}

- (void)callback
{
    NSLog(@"call back selector");
}

- (void)doSomethingWithCompletionSelector:(SEL)selector
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
        NSLog(@"Doing something");
        // Causes a warning in ARC
        [self performSelector:selector];
    });
}

- (void)doSomethingWithCompletionFunction:(void (*)())function
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Doing something");
        function();
    });
}

@end