How to get the value of a variable in blocks

Is it still necessary to check the value of the variable 'type' with completeHandler.

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

I wrote a small piece of code to check if it works (just reading your question I would say yes like Droppy)

I added all the code in the ViewController in the Simple View application. some suggestions: - all the code is there for the sake of simplicity .... - I added a singleton, since it seems like you are calling a class method. - the instance method is a little rude, it just saves the name and blocks - I added a typedef for the blocks to read it better.

#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);
     }
 }];
}

he writes the log correctly

0

Source: https://habr.com/ru/post/1649413/


All Articles