如何在块中获取变量的值

时间:2016-07-28 13:42:10

标签: ios objective-c xcode objective-c-blocks

无论如何都要检查' type'的价值。变量with completionHandler。

-(void)sendApiMethod:(NSString*)apiName ApiType:(NSString*)type
{
 [SendAPI setAPIWithName:@"APIName" completionHandler:^(NSArray *errors) {
        if([type isEqualToString:@"Login"])
        {
           /// Call Some Other function
        }
    }];
}

1 个答案:

答案 0 :(得分:0)

我写了一小段代码来验证是否有效(只读你的问题,我会说是Droppy)

我在Simple View App的ViewController中添加了所有代码。 一些假设: - 所有代码都是为了简洁.... - 我已经添加了一个单例,因为它似乎正在调用一个类方法。 - 实例方法有点粗糙,它只是保存名称和块 - 我为块添加了一个typedef以便更好地阅读它。

#import "ViewController.h"



typedef void (^CompletionBlock)(NSArray *errors);


@interface SendAPI : NSObject

-(void)setAPIWithName:(NSString*)name completionHandler: (CompletionBlock)completionHandler;
+(void)setAPIWithName:(NSString*)name completionHandler: (CompletionBlock)completionHandler;
+(SendAPI*)sharedInstance;

@property (strong) CompletionBlock completionBlock;
@property (strong) NSString * name;

@end


@implementation SendAPI : NSObject

static SendAPI * _singleton = nil;



+(SendAPI*)sharedInstance
{
    if (_singleton == nil)
    {
        _singleton = [[SendAPI alloc] init];
    }
    return _singleton;
}


-(void)setAPIWithName:(NSString*)name completionHandler: (CompletionBlock)completionHandler;
{
    self.completionBlock = completionHandler;
    self.name = [name copy];

    __weak SendAPI * weakRef = self;


    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        NSError* err = [NSError errorWithDomain: @"delayed"
                                           code:1111
                                       userInfo: @{@"info": self.name}
                        ];

        weakRef.completionBlock(@[err]);

    });

}


+(void)setAPIWithName:(NSString*)name completionHandler: (CompletionBlock)completionHandler;
{
    [[SendAPI sharedInstance]setAPIWithName:name completionHandler:completionHandler];

}


@end





@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self sendApiMethod:@"HELLO" ApiType: @"Login"];
}




-(void)sendApiMethod:(NSString*)apiName ApiType:(NSString*)type{

    [SendAPI setAPIWithName:@"APIName" completionHandler:^(NSArray *errors) {
     if([type isEqualToString:@"Login"])
     {
         /// Call Some Other function
         NSLog(@"%@", errors);
     }
 }];
}

它正确记录