ios - What does NSRunLoop do? -
i read many posts nsrunloop, this, this, this. can't figure out nsrunloop does
what see worker thread
wthread = [[nsthread alloc] initwithtarget:self selector:@selector(threadproc) object:nil]; [wthread start]; with nsrunloop inside it
- (void)threadproc { nsautoreleasepool* pool1 = [[nsautoreleasepool alloc] init]; bool isstopped = no; nsrunloop *runloop = [nsrunloop currentrunloop]; [runloop addport:[nsmachport port] formode:nsdefaultrunloopmode]; while (!isstopped) { { nsautoreleasepool* pool2 = [[nsautoreleasepool alloc] init]; [runloop runmode:nsdefaultrunloopmode beforedate:[nsdate distantfuture]]; [pool2 release]; } } [pool1 release]; } and main thread passes work wthread
[self performselector:@selector(somework:) onthread:wthread withobject:nil waituntildone:no]; in term of passing work main thread worker thread, see many people this. why need nsrunloop here ? ?
i read nsrunloop used manage events, why there nothing except calling runmode inside threadproc ?
the example you've shown cocoa idiom creating thread continue run after method -threadproc exits. why?
because:
- the
nsrunloopinstance you've created has @ least 1 input source ([nsmachport port]) - you've explicitly started run loop
runmode:beforedate
without adding input source , explicitly starting run loop, thread terminate.
parenthetically, although run loops still vital managing events , asynchronous tasks, not view nsthread default way of architecting asynchronous work in cocoa app nowadays. gcd far cleaner way of encapsulating background work.
edit:
submitting work serial queue in gcd:
@interface foo : nsobject @end @implementation foo { dispatch_queue_t _someworkerqueue; } - (id)init { self = [super init]; if( !self ) return nil; _someworkerqueue = dispatch_queue_create("com.company.myworkerqueue", 0); return self; } - (void)performjob { dispatch_async(_someworkerqueue, ^{ //do work asynchronously here }); dispatch_async(_someworkerqueue, ^{ //more asynchronous work here }); } @end
Comments
Post a Comment