怎么在一个线程结束后回到主线程?
我用一个for循环上传三张照片(用的是afnetworking框架)。
上传它就开了一个线程,上传成功后后台返回一个filename,把filename放进一个数组
我想等三张照片全都上传结束后,对获取到的三个filename进行操作
要怎么做?
NSMutableArray *fileNameArr = [[NSMutableArray alloc]init];
for (int i= 0; i<[self.imgArr count]; i++) {
NSData *data = [self.imgArr objectAtIndex:i];
[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
[formData appendPartWithFileData:data name:@"pic" fileName:fileName mimeType:@"image/jpeg"];
}success:^(AFHTTPRequestOperation *operation,id responseObject){
NSLog(@"success:%@",responseObject);
NSString *str = [[responseObject objectForKey:@"data"] objectForKey:@"fileName"];
[fileNameArr addObject:str];
NSString *ids = [[responseObject objectForKey: @"data"] objectForKey:@"ids"];
}
failure:^(AFHTTPRequestOperation *operation,NSError *error){
NSLog(@"%@",error);
}];
}
soraoto
9 years, 9 months ago
Answers
第一种是Notification,这个比较解耦。
-(void)viewDidLoad
{
// add a notification observer
[NSNotificationCenter defaultCenter] addObserver:selector:name:object:]
}
-(void)handle
{
if (fileNameArr.count == 3) {
// do something
}
}
NSMutableArray *fileNameArr = [[NSMutableArray alloc]init];
for (int i= 0; i<[self.imgArr count]; i++) {
NSData *data = [self.imgArr objectAtIndex:i];
[manager POST:url
parameters:nil
constructingBodyWithBlock:
^(id<AFMultipartFormData> formData){
[formData appendPartWithFileData:data
name:@"pic"
fileName:fileName
mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation,id responseObject) {
NSLog(@"success:%@",responseObject);
NSString *str = [[responseObject objectForKey:@"data"] objectForKey:@"fileName"];
[fileNameArr addObject:str];
NSString *ids = [[responseObject objectForKey: @"data"] objectForKey:@"ids"];
// add here
[NSNotificationCenter defaultCenter] postNotificationName:object:]
} failure:^(AFHTTPRequestOperation *operation,NSError *error){
NSLog(@"%@",error);
}];
}
第二种就是,GCD啦,但是代码看起来耦合比较高。
NSMutableArray *fileNameArr = [[NSMutableArray alloc]init];
for (int i= 0; i<[self.imgArr count]; i++) {
NSData *data = [self.imgArr objectAtIndex:i];
[manager POST:url
parameters:nil
constructingBodyWithBlock:
^(id<AFMultipartFormData> formData){
[formData appendPartWithFileData:data
name:@"pic"
fileName:fileName
mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation,id responseObject){
NSLog(@"success:%@",responseObject);
NSString *str = [[responseObject objectForKey:@"data"] objectForKey:@"fileName"];
[fileNameArr addObject:str];
NSString *ids = [[responseObject objectForKey: @"data"] objectForKey:@"ids"];
// here
if (fileNameArr.count == 3) {
dispatch_async(dispatch_get_main_queue(), ^{
// handle
});
}
} failure:^(AFHTTPRequestOperation *operation,NSError *error){
NSLog(@"%@",error);
}];
}
2010注册
answered 9 years, 9 months ago