皆さんが私を助けてくれることを願っています:)
メイン スレッドで NSOperation を作成し、それをキューに追加します。その操作は、NSURLConnection を使用してデータ サーバーに接続し、receivedData を保存して解析することです。
Operation.m
- (void)start
{
NSLog(@"opeartion for <%@> started.", [cmd description]);
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", m_BOUNDARY] forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:_postData];
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (_connection == nil)
[self finish];
}
次に、この NSURL デリゲート メソッドで、サーバーから受け取ったばかりのデータを解析します。
Operation.m
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self parseItems];
}
データには、たとえば、到着時に描画するためにメイン スレッドに送信する screenItem、CellItem、TextItem などの項目があります。(itemTable が届いたら UITableView を作成し、itemWeb が届いたら UIWebView を作成します)
これを使用して、アイテムをメインスレッドに送信します。
Operation.m
- (void) parseItems
{
while ([_data length] > 0)
{
NSInteger type = [self _readByte];
switch (type)
{
case SCREEN:
{
[self _send: [self _readScreen]];
break;
}
case CELL:
{
[self _send: [self _readCell]];
break;
}
// ... A lot of different items
}
}
}
- (void)_send:(CItem*)_item
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"newItem" object:_item];
}
次に、通知レシーバーで:
AppDelegate.m
- (void) _newItemArrived:(NSNotification *) notification
{
[self performSelectorOnMainThread:@selector(processItem:) withObject:[notification object] waitUntilDone:NO];
}
私の問題は、NSOperation が終了するまで UI が描画されないことです。別のスレッドである NSOpertion はメイン スレッドをブロックしないと思いましたが、それが起こっていることだと思います。
この問題のヒントはありますか?
読んでくれてありがとう!