[NSThread sleepForTimeInterval:1.0];このsleepForTimeInterval:というのは、スレッドを「スリープ」させるものです。引数で指定した秒数だけ、スレッドの実行を停止します。まぁ、このサンプルではなくてもいいんですが、そうするとほとんど瞬時に処理が終わってしまうので、「え? 今、本当に並行して複数の処理が動いてたの?」と頭の周りを???がぐるぐる回ることになりかねないため、これでときどき止めながら動かしていたわけです。
[NSThread detachNewThreadSelector:@selector(printMessage:)セレクタには、@selector(printMessage:)というようにしてprintMessage:を指定しています。ターゲットはMyTestClassインスタンスが収められた変数。そしてメソッドの引数にNSStringを用意しています。これで、後は放っておくだけ。勝手に処理を実行していってくれるのです。
toTarget:obj1 withObject:@"first"];
※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
※MyTestClass.h
#import <Cocoa/Cocoa.h>
@interface MyTestClass : NSObject {
int count;
int endcount;
}
+(MyTestClass*)myTestClassToEndCount:(int)n;
-(void)setEndCount:(int)n;
-(void)printMessage:(NSString*)s;
@end
#import <Foundation/Foundation.h>
@interface MyTestClass : NSObject {
int count;
int endcount;
}
+(MyTestClass*)myTestClassToEndCount:(int)n;
-(void)setEndCount:(int)n;
-(void)printMessage:(NSString*)s;
@end
※MyTestClass.m
#import "MyTestClass.h"
@implementation MyTestClass
+(MyTestClass*)myTestClassToEndCount:(int)n {
MyTestClass* obj = [[MyTestClass alloc] init];
[obj setEndCount:n];
return obj;
}
-(void)setEndCount:(int)n {
endcount = n;
}
-(void)printMessage:(NSString*)s {
BOOL flg = YES;
while (flg) {
[NSThread sleepForTimeInterval:1.0];
NSLog(@"%@:%i",s,++count);
if (endcount == count) {
flg = NO;
NSLog(@"end...");
}
}
}
@end
※main関数のソースコード
#import <Foundation/Foundation.h>
#import "MyTestClass.h"
int main (int argc, const char * argv[]) {
@autoreleasepool {
MyTestClass* obj1 = [MyTestClass
myTestClassToEndCount:5];
MyTestClass* obj2 = [MyTestClass
myTestClassToEndCount:3];
[NSThread detachNewThreadSelector:
@selector(printMessage:)
toTarget:obj1 withObject:@"first"];
[NSThread detachNewThreadSelector:
@selector(printMessage:)
toTarget:obj2 withObject:@"second"];
NSLog(@"start!!");
// 終了しないようにしておく
[[NSRunLoop currentRunLoop] run];
}
return 0;
}
| << 前へ | 次へ >> |