我试图在for循环中调用dispatch_async队列。每个循环都会添加一个新队列。
queue1 = dispatch_queue_create("com..queue1", DISPATCH_QUEUE_CONCURRENT);
for(NSDictionary *dictInfo in dataArray) {
dispatch_async(queue1,^(void) {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
HeaderValueGenerator *valueGenerator = [HeaderValueGenerator instance] ;
valueGenerator.apiPath = @"path";
valueGenerator.request = request;
[request addValue:[valueGenerator createSignature] forHTTPHeaderField:@"X-Authorization-Client"];
//request is used to call the server. (asynchronous call and hence inside dispatch_async)
}
}
该请求用于对服务器进行异步调用。服务器以不匹配的签名响应。某些请求不会运行createSignature方法。
以下是线程安全的单例。我使用单例作为不同API调用的各种NSURLRequest的共享资源。所以我无法在所有请求对象中定义它,而是使用这个单例调用它们。
HeaderValueGenerator.h
#import <CommonCrypto/CommonHMAC.h>
@interface HeaderValueGenerator : NSObject
@property (nonatomic,strong) NSString *apiPath;
@property (nonatomic,strong) NSMutableURLRequest *request;
+ (HeaderValueGenerator *)instance;
- (NSString *)createSignature;
@end
HeaderValueGenerator.m
+ (HeaderValueGenerator *)sharedInstance {
static HeaderValueGenerator *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return sharedInstance;
}
- (NSString *)createSignature {
// String hashing and data encoding the header values for special header fields
return SignedString;
}
当这个程序运行for循环时,一些循环不会执行createSignature方法。结果我得到了服务器的错误响应。有没有更好的方法来使用dispatch_async? 有僵局吗?
修改
-(void)createSignature{
@synchronized(self) {
// ... do stuff ...
}
}
这会有帮助吗?在synchronized(self)
?