NSString *url = @"http://localhost/xml";
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[NSURLConnection sendAsynchronousRequest:req queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLData:data error:&error];
int count = [[[xmlDictionary objectForKey:@"ArrayOfMessage"] objectForKey:@"Message"] count];
if(true && count > 5) count = 5;
UIScrollView *sv = [[UIScrollView alloc] initWithFrame:CGRectMake(58, 0, MESSAGE_PAGING_WIDTH, 493)];
[sv setBounces:YES];
[sv setClipsToBounds:NO];
[sv setPagingEnabled:YES];
[sv setShowsHorizontalScrollIndicator:FALSE];
[sv setContentSize:CGSizeMake(count * MESSAGE_PAGING_WIDTH, frame.size.height)];
int i = 0;
while (i < count) {
NSDictionary *data = [[[xmlDictionary objectForKey:@"ArrayOfMessage"] objectForKey:@"Message"] objectAtIndex:i];
[sv addSubview:[[MessageView alloc] initWithFrame:CGRectMake(i * MESSAGE_PAGING_WIDTH, 0, 838, 493) data:data]];
++i;
}
[self addSubview:sv];
}];
I get a crash message of:
bool _WebTryThreadLock(bool), 0x7d7d080: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...
How can I remedy?
You’re creating UIKit elements on a different thread than the main thread:
sendAsynchronousRequest:queue:completionHandler:performs on a background thread. Inside your block you need to useperformSelectorOnMainThread:withObject:waitUntilDone:for UIKit objects.See http://blog.jayway.com/2010/03/30/performing-any-selector-on-the-main-thread/