我想通過使用enumerateObjectsWithOptions:usingBlock
方法的數組來枚舉。但是,我的代碼很少有效。當它不起作用時,我的應用程序凍結(但沒有沙灘球) - 我對塊的相對較新,所以我必須錯過塊操作順利進行所需的一些東西。enumerateObjectsWithOptions:usingBlock:引起頻繁不明原因的凍結
注:我知道我可以使用for
循環來枚舉,但這不是我正在尋找的。
的麻煩代碼:
NSArray*_storageCookies = [[NSArray alloc] initWithArray:[storage cookies]];
NSArray*_historyObjects = [[NSArray alloc] initWithArray:[_history webkitHistory]];
NSOperationQueue*_queue = [[NSOperationQueue alloc] init];
NSBlockOperation*_block = [NSBlockOperation blockOperationWithBlock:^{
NSAutoreleasePool*_pool = [[NSAutoreleasePool alloc] init];
[_storageCookies enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id ck, NSUInteger index, BOOL *stop)
{
NSString*domain = [ck domain];
[_historyObjects enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id object, NSUInteger aindex, BOOL *stop)
{
@synchronized(self)
{
NSAutoreleasePool*_pool2 = [[NSAutoreleasePool alloc] init];
NSString*_historyURL = [[NSURL URLWithString:[object url]] host];
if ([_historyURL rangeOfString:domain].location != NSNotFound)
{
NSHTTPCookie*cookie = [DAHTTPCookie createCookieWithURL:[ck domain] cookieName:[ck name] expires:[[ck expiresDate] timeIntervalSince1970] cookieValue:[ck value] browserType:DAWebkitBrowser secure:[ck isSecure]];
if ([_cookies containsObject:cookie] == NO)
{
[_cookies addObject:cookie];
}
}
[_pool2 release];
}
}];
}];
[_pool release];
}];
[_queue addOperations:[NSArray arrayWithObject:_block] waitUntilFinished:YES];
NSLog(@"Done - found %i Cookies...",[_cookies count]); //sometimes returns 0, sometimes the right number or nothing
編輯
我有固定它。你是對的,我的班級不是線程安全的。所以我必須添加一個@synchronized
塊才能按預期工作。
您仍在使用潛在的爆炸性併發算法。雖然現在起作用,但它很可能是非常無效的。 – bbum 2011-12-26 17:00:10
好吧 - 我會如何加油?我是新來的這種枚舉,所以我很欣賞你可以給的任何建議! – Pripyat 2011-12-26 18:56:13