2010年11月2日火曜日

Objective-C + libxml2 を使ってフィードを取り込みたいんだ(9)

なんかもうlibxml2のことは関係なく普通にObjective-Cの勉強になってる。

今回は、
  • NSOperationQueue
  • NSOperation
  • NSNotificationCenter
  • NSNotification

に焦点をあわせる。

でもNSNotificationの辺りは
「Cocoa Notification (NSNotification,NSNotificationCenter)」と「キー値監視」(1~4)
に書いてるので省略。
1つだけ注意するのは、通知の受け取りをメインスレッドで行ないたい場合は、通知する側でperformSelectorOnMainThread:withObject:を使って通知を投げる必要あり。


NSOperationQueueとNSOperationについてもあまり書く事はないんだけど続ける。
覚えたこと。
  • 並列と非並列とがある。
  • キューにNSOperationのインスタンスを貯めて置いて、順番に処理を起動していく。
  • 並列は、1つの処理の完了を待たずに次の処理を起動する。(複数の別スレッドで処理される)
  • 非並列は、1つの処理が完全に終了するまで次の処理を起動しない。(全てメインスレッドで処理される)
  • iOS4からは[[NSOperationQueue alloc] init]で初期化した場合は、並列になる。NSOperationなインスタンスのisConcurrentの値は関係なく。
  • iOS4で非並列に処理させたい場合は、[NSOperation mainQueue] ってやる。


注意すること。
並列で処理実行するときは、NSRunLoopの実行ループをループさせておいてのイベント処理が必要な場合がある(間違ってるかも)。
今回は必要なのでRunLoop入れてあります。


あーもう、ぐちゃぐちゃだーーー!!!
あとはソース見てください。


次回の内容は未定。



Xcode 3.2.4 and iOS SDK 4.1 で試してる。
古いバージョンとか新しいバージョンのこと考えてない。

新規プロジェクトをView-based Applicationを選択して名前をMyOperationとして作成してます。
新規ファイル追加で、NSOperationを継承したMyClassを作成しています。

  1. //  
  2. //  MyOperationViewController.h  
  3. //  
  4. #import <uikit uikit.h="">  
  5.   
  6. @interface MyOperationViewController : UIViewController {  
  7. }  
  8. @end  
  9. </uikit>  

  1. //  
  2. //  MyOperationViewController.m  
  3. //  
  4. #import "MyOperationViewController.h"  
  5. #import "MyClass.h"  
  6.   
  7. @implementation MyOperationViewController  
  8.   
  9. - (void)owatayo:(MyClass *)obj  
  10. {  
  11.     //NSLog(@"%@", obj);  
  12.     //NSLog(@"no.%d", [[(MyClass *)[obj object] number] intValue]);  
  13.     NSNumber *num = [[obj userInfo] objectForKey:@"number"];  
  14.     NSLog(@"[no.%d] メインスレッド:通知owataを受け取ってowatayoメソッドを実行したよ。", [num intValue]);  
  15. }  
  16.   
  17. - (void)viewDidLoad  
  18. {  
  19.     [super viewDidLoad];  
  20.   
  21.     // 読み込むフィード  
  22.     NSString *feedURL1 = @"http://eyesrobe.blogspot.com/feeds/posts/default?alt=rss";  
  23.     NSString *feedURL2 = @"http://blog.eyesrobe.com/feed/rss";  
  24.     NSArray *feeds = [NSArray arrayWithObjects:feedURL1, feedURL2, feedURL1, feedURL2, feedURL1, feedURL2, feedURL1, feedURL2, nil];  
  25.       
  26.     // 通知  
  27.     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];  
  28.   
  29.     // キューの初期化  
  30.     NSOperationQueue *queue = [[NSOperationQueue alloc] init];  
  31.   
  32.     // NSOperationQueue に許す同時接続スレッドの数  
  33.     // スレッド数を制限した場合としない場合の実行内容を比較してみるといいかも。  
  34.     [queue setMaxConcurrentOperationCount:3];  
  35.   
  36.     // キューにNSOperationなオブジェクトを追加する。  
  37.     // 追加されたオブジェクは別スレッドで順に処理されていく。  
  38.     int i=0;  
  39.     for (NSString *feedURL in feeds) {  
  40.   
  41.         NSURLRequest *requestURL = [NSURLRequest requestWithURL:[NSURL URLWithString:feedURL]];  
  42.         MyClass *obj = [[MyClass alloc] initWithRequest:requestURL];  
  43.         obj.number = [NSNumber numberWithInt:(++i)];  
  44.         [center addObserver:self selector:@selector(owatayo:) name:@"owata" object:obj];  
  45.         [queue addOperation:obj];  
  46.         [obj release];  
  47.     }  
  48.   
  49.     // キューが全て処理されるまで待つメソッド  
  50.     // [queue waitUntilAllOperationsAreFinished];  
  51.     //  
  52.     // 待たないで処理をバックグラウンドで処理するのであれば、NSNotificationCenterなど  
  53.     // を使ってバックグラウンド処理完了の通知を受け取ることが多いみたい。  
  54.       
  55.     [queue release];  
  56. }  
  57.   
  58. - (void)didReceiveMemoryWarning {  
  59.     [super didReceiveMemoryWarning];  
  60. }  
  61.   
  62. - (void)viewDidUnload {  
  63. }  
  64.   
  65. - (void)dealloc {  
  66.     [super dealloc];  
  67. }  
  68.   
  69. @end  

  1. //  
  2. //  MyClass.h  
  3. //  
  4. #import <foundation foundation.h="">  
  5.   
  6. @interface MyClass : NSOperation {  
  7.     NSNumber *number;  
  8.     NSURLRequest *requestURL;  
  9.   
  10.     BOOL done;  
  11. }  
  12.   
  13. @property (nonatomic, retain) NSNumber *number;  
  14. @property (nonatomic, retain) NSURLRequest *requestURL;  
  15.   
  16. - (id)initWithRequest:(NSURLRequest *)requestURL_;  
  17.   
  18. @end  
  19. </foundation>  

  1. //  
  2. //  MyClass.m  
  3. //  
  4. #import "MyClass.h"  
  5.   
  6. @implementation MyClass  
  7.   
  8. @synthesize number;  
  9. @synthesize requestURL;  
  10.   
  11. /** 
  12.  * 初期化 
  13.  */  
  14. - (id)initWithRequest:(NSURLRequest *)requestURL_  
  15. {  
  16.     self = [super init];  
  17.     if (self != nil) {  
  18.         self.requestURL = requestURL_;  
  19.     }  
  20.       
  21.     return self;  
  22. }  
  23.   
  24. /** 
  25.  * キューに追加されることで実行されるメソッド 
  26.  */  
  27. - (void)main  
  28. {  
  29.     NSLog(@"[No.%d] MyClass::main", [self.number intValue]);  
  30.   
  31.     // NSURLConnection  
  32.     NSURLConnection *urlConnection = [[[NSURLConnection alloc] initWithRequest:self.requestURL delegate:self] autorelease];  
  33.   
  34.     if (urlConnection == nil) {  
  35.         NSLog(@"error");  
  36.     }  
  37.     else {  
  38.         // データ受信完了フラグ  
  39.         done = NO;  
  40.       
  41.         // NSOperationQueueで別のスレッド動かす場合、NSAutoreleasePoolは要らないみたいだけど、NSRunLoop(実行ループ?)は必要っぽい。  
  42.         // 処理実行中(done==NO)の間は、実行ループをループさせ続けることが必要。  
  43.         // ここでは、NSURLConnectionによるデータ受信完了時点で処理完了(done=YES)としている。  
  44.         do {  
  45.             [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];  
  46.         } while (!done);  
  47.     }  
  48.   
  49.     // 通知するときに一緒に送りたいメッセージ  
  50.     NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:number, @"number", @"value", @"key", nil];  
  51.   
  52.     // 処理が終わったら通知メッセージを送る。  
  53.     // メインスレッドで実行させたいので performSelectorOnMainThread:withObject:waitUntilDone: を使った。  
  54.     NSNotification *notification = [NSNotification notificationWithName:@"owata" object:self userInfo:dict];  
  55.     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];  
  56.     [center performSelectorOnMainThread:@selector(postNotification:) withObject:notification waitUntilDone:NO];  
  57. }  
  58.   
  59. /** 
  60.  * データ受信 
  61.  */  
  62. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {  
  63.     NSLog(@"[No.%d] 受信中(データは分割されて受信される)", [self.number intValue]);  
  64. }  
  65.   
  66. /** 
  67.  * 受信完了 
  68.  */  
  69. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {  
  70.     NSLog(@"[No.%d] 受信完了", [self.number intValue]);  
  71.     done = YES;  
  72. }  
  73.   
  74. /** 
  75.  * 受信エラー 
  76.  */  
  77. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {  
  78.     NSLog(@"エラー");  
  79. }  
  80.   
  81. /** 
  82.  * dealloc 
  83.  */  
  84. - (void)dealloc {  
  85.     [number release];  
  86.     [requestURL release];  
  87.     [super dealloc];  
  88. }  
  89.   
  90. @end  


たぶん続く。

0 件のコメント:

コメントを投稿