2013年2月3日日曜日

[iOS]NSAutoreleasePoolじゃなくて@autoreleasepool。UIActivityIndicatorをまわす

過去のみなさんも結構はまってるみたいですが、
同じように見事はまりました。
今はNSAutoreleasePoolじゃなくて、@autoreleasepoolを使います。
UIActivityIndicatorをまわす

要は、
1.画面に表示させるものはメインスレッドで、裏で行う動作を他のスレッドにまわすということ。
2. 'NSAutoreleasePool' is unavailable: not available in automatic reference counting mode のエラーで既に使えないということ
3.同時にautoreleasepoolとメインスレッドの処理を行う(インディケータをまわす)とインディケータはうまく表示されないということ


ボタンがおされたあとの処理
- (void)setIndicator{
// viewDidLoadに[self setIndicator]を指定

//インディケータを作成
 CGRect bounds = [[UIScreen mainScreen] applicationFrame];
// UIActivityIndicatorView *indicator
 indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

 [indicator setCenter:CGPointMake(bounds.size.width/2, bounds.size.height/2)];
 
//ビューに追加
 [self.view addSubview:indicator];
}


-(IBAction)Button:(id)sender{
[self.indicator startAnimating];
 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(doInBackground) userInfo:nil repeats:NO];
 NSLog(@"Timer Status:%d", [timer isValid]);
}

-(void)doInBackground{

 @autoreleasepool {
  //裏で動かす処理
 }
}

NSTimerをいれてインディケータを表示させてから表示させること。
裏で動かすスレッドは@autorelesepoolの中に処理内容を書いてあげること。



参考
[iOS] UIActivityIndicatorViewでハマった件

ARCを有効にした状態でperformSelectorInBackground:withObjectを使う