2016-07-28 104 views
4

有無論如何用completionHandler檢查'type'變量的值。如何獲得塊內變量的值

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

是;該代碼將起作用。該塊將在創建時獲取'type'的副本。 – Droppy

+0

@Droppy當我嘗試獲取類型變量的值時,它顯示我'無'。 – user3223139

+0

它在塊執行之前是非'nil'? – Droppy

回答

0

我寫了一小段代碼來驗證作品(僅讀出你的問題我會說是因爲Droppy)

我添加了所有的代碼有一個視圖控制器在一個簡單的查看程序。 一些假設: - 所有的代碼爲了semplicity .... - 我已經添加了一個單身,因爲它似乎你正在調用一個類的方法。 - 實例方法有點粗糙,它只是保存名稱和塊 - 我添加了塊的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); 
    } 
}]; 
} 

它LOG正確