我有这个方法
- (NSString*) createUserWithName:(NSString*)TheName
{
NSURL *URL =someUrlthatIncludesTheName
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *URL = [NSURL URLWithString:url];
NSURLSessionTask *task = [session dataTaskWithURL:URL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (response) {
NSError* error = nil;
NSArray *output = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
myID = [[output objectAtIndex:0] objectForKey:@"UserID"];
}
}];
[task resume];
return myID;
}另一种方法
-(void)doSomethingWith: (NSString*) anID在我的代码中,我随后调用了这些方法,如下所示:
[self createUserWithName:@"John"];
[self doSomethingWith:myID];但是,由于createUserWithName:中的createUserWithName:是异步的,所以doSomethingWith:是用myID = (null)触发的。
解决这个问题的最佳方法是什么,而不一定回到不受欢迎的同步NSURLConnection?
提前感谢
发布于 2016-04-02 14:12:28
工作流应该是
- (void)createUserWithName:(NSString*)TheName
{
NSURL *URL =someUrlthatIncludesTheName
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *URL = [NSURL URLWithString:url];
NSURLSessionTask *task = [session dataTaskWithURL:URL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (response) {
NSError* error = nil;
NSArray *output = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
myID = [[output objectAtIndex:0] objectForKey:@"UserID"];
[self doSomethingWith:myID];
}
}];
[task resume];
}这个电话只是
[self createUserWithName:@"John"];方法doSomethingWith:是在完成块中异步执行的。
或者使用自定义完成块。
- (void)createUserWithName:(NSString *)theName completion:^(NSString *identifier)completion
{
NSURL *URL =someUrlthatIncludesTheName
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *URL = [NSURL URLWithString:url];
NSURLSessionTask *task = [session dataTaskWithURL:URL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (response) {
NSError* error = nil;
NSArray *output = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
myID = [[output objectAtIndex:0] objectForKey:@"UserID"];
completion(myID);
}
}];
[task resume];
}然后用它
[self createUserWithName:@"John" completion:^(NSString *identifier) {
[self doSomethingWith:identifier];
}];https://stackoverflow.com/questions/36374263
复制相似问题