带参数的完成块

4

我在NSObject类中编写了一个带有完成块(completion block)的方法,并从UIViewController中调用此方法,它完美运行。但是我如何在此方法中传递一个NSString参数?下面是我的代码片段:

-(void)testingFunction:(void(^)(NSMutableArray* result))handler{
    NSMutableArray *dataArray = [[NSMutableArray alloc] init];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstring]];
    NSString *authStr = @"";
    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
    [request setValue:authValue forHTTPHeaderField:@"Authorization"];

    //create the task
    NSURLSessionDataTask* task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    [dataArray addObject:[[json objectForKey:@"query"] objectForKey:@"geosearch"]];
    dispatch_async(dispatch_get_main_queue(), ^{
        handler(dataArray) ;
      });
    }];
    [task resume];
}

我需要从我的UIViewController中调用此方法。
[[AllFunction sharedInstance] testingFunction:^(NSMutableArray* testResult){
    [somearray addObject:testResult];
    NSLog(@"Result was %@", somearray);
    [self.tableView reloadData];
}];

1
但是你已经传递了一个参数,那么传递另一个参数有什么困难吗? - trojanfoe
你想将 NSString* 传递给 testingFunction 还是传递给 block? - Moumou
是的,我想将NSString传递给testingFunction函数。 - A.T
@trojanfoe,我正在尝试这个功能,但是它给我报错。-(void)testingFunction:(void(^)(NSMutableArray* result))handler:(NSString*)urlstring - A.T
@Anirban,我刚刚发布了一个答案。在 :(NSString)urlstring* 之前,你忘记了什么吗? :) - Moumou
@kimimsc 我想从我的视图控制器中传递这个 (NSString*)urlstring。 - A.T
2个回答

6
如果你想将一个NSString*传递给方法:
-(void)testingFunction:(void(^)(NSMutableArray* result))handler andString:(NSString*) yourString;

如果你想将一个NSString*传递给完成块:

-(void)testingFunction:(void(^)(NSMutableArray* result, NSString* yourString))handler;

编辑:

您可以像这样调用该方法:

NSString* yourString = @"Some Text";
testingFunction:^(NSMutableArray* result) {
    //Do whatever you want here
} andString:yourString;

请阅读:http://www.tutorialspoint.com/objective_c/objective_c_functions.htm

编辑2:

trojanfoe所说,如果您的字符串应该是一个url,则应使用NSURL而不是NSString


谢谢kimimsc,我想要的是第一个,但你能否请解释一下我该如何调用这个方法?这将非常有帮助。 - A.T
非常感谢,它有效了。很抱歉我没有足够的声望来给你投票 :( - A.T

0

由于这个“string”实际上是一个URL,因此应该传递一个NSURL实例:

-(void)testingFunction:(void(^)(NSMutableArray* result))handler
               withURL:(NSURL *)url
{
    NSMutableArray *dataArray = [[NSMutableArray alloc] init];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    ....
}

然而,我不确定为什么你的问题标题是“带参数的完成块”,因为这个问题涉及到一个普通的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接