gpt4 book ai didi

objective-c - 带参数的完成 block

转载 作者:行者123 更新时间:2023-12-03 21:32:43 26 4
gpt4 key购买 nike

我在 nsobject 类中编写了一个带有完成块的方法,并从 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];
}];

最佳答案

如果你想通过一个 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

关于objective-c - 带参数的完成 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32587614/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com