我在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];
}];
答案 0 :(得分:4)
如果您想将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
<强> EDIT2:强>
正如 trojanfoe 所说,如果你的字符串应该是一个网址,你应该使用NSURL
而不是NSString
答案 1 :(得分:0)
正如此&#34;字符串&#34;实际上是一个URL,而是传递NSURL
实例:
-(void)testingFunction:(void(^)(NSMutableArray* result))handler
withURL:(NSURL *)url
{
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
....
}
但是,我不确定为什么你的问题符合&#34;带参数的完成块&#34;因为这个问题与普通方法有关。