2017-05-09 8 views
0

まず、私は弱い性質を持っています。メインスレッドではないスレッドを指します。なぜ新しいスレッドがメインスレッドを指しているのですか?

@property (nonatomic, weak) id weakThread; 

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    // Override point for customization after application launch. 
    { 
     NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun) object:nil]; 
     self.weakThread = thread; 
     [thread start]; 
    } 
    NSLog(@"main: %@, %p", self.weakThread, self.weakThread); 
    return YES; 
} 

- (void)threadRun { 
    NSLog(@"current: %@, %p", [NSThread currentThread], [NSThread currentThread]); 
    NSLog(@"self.weakThread in thread: %@, %p", self.weakThread, self.weakThread); 
} 

これらのコードを見てください。実行後、出力されます:

main: <NSThread: 0x608000278240>{number = 5, name = main}, 0x608000278240 
current: <NSThread: 0x608000278240>{number = 5, name = (null)}, 0x608000278240 
self.weakThread in thread: <NSThread: 0x608000278240>{number = 5, name = (null)}, 0x608000278240 

ポインタは決して変更されません。しかし、スレッドが変更されます。私はなぜそれがメインスレッドに変更されているのか分からない。 最初の出力が表示され、nameはmainです。

答えて

1

実際にはコード内のself.weakThread[NSThread currentThread]は同じなので、ポインタを変更する必要はありません。それはメインスレッドに変更されませんでした(名前 'メイン'は偽物です)。あなたは、スレッドに名前を割り当てることによって、それを証明することができます

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun) object:nil]; 
thread.name = @"a thread"; 

結果が

"{number = 5, name = a thread}". 

に変更され、あなたが本当のメインスレッドがによって異なるアドレスを持っていることがわかります:

NSLog(@"real main: %@", [NSThread mainThread]); 
NSLog(@"my thread: %@", self.weakThread); 
関連する問題