Objective c 目标C:NSThread需要什么样的样板代码?

Objective c 目标C:NSThread需要什么样的样板代码?,objective-c,nsthread,boilerplate,Objective C,Nsthread,Boilerplate,我发现NSThread上的文档对NSThread中的新手没有太多的信息,而且我没有看到任何“这是样板代码”,其中包含了使用nsrunlop的NSThread的所有代码。《编程指南》中散布了许多代码片段 启动新的NSThread的好样板示例是什么样子的?每个NSThread本身都可以提供一个nsrunlop,因此无需编写任何内容。您真正需要关心的是定期泵送nsrunlop(假设您没有附加任何隐式为您执行此操作的对象,例如NSTimer) 例如 // create a thread and poin

我发现
NSThread
上的文档对
NSThread
中的新手没有太多的信息,而且我没有看到任何“这是样板代码”,其中包含了使用
nsrunlop
的NSThread的所有代码。《编程指南》中散布了许多代码片段


启动新的
NSThread
的好样板示例是什么样子的?

每个
NSThread
本身都可以提供一个
nsrunlop
,因此无需编写任何内容。您真正需要关心的是定期泵送nsrunlop(假设您没有附加任何隐式为您执行此操作的对象,例如
NSTimer

例如

// create a thread and point it to an agent that
// knows how to pump the run loop
myThread = [[NSThread alloc] initWithTarget:self
                selector:@selector(startRunLoop)
                object:nil];

// start the thread
[serialDispatchThread start];

/* ... elsewhere ... */
- (void)startRunLoop
{
    // consider setting a thread name here, as it'll help with debugging

    // I'm lazily using a volatile bool for my quit flag; do whatever you
    // think is appropriate
    while(!quitThread)
    {
        // run the runloop for another 2 seconds, 
        // wrapping it in an autorelease pool
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

        [[NSRunLoop currentRunLoop] runUntilDate:
                [NSDate dateWithTimeIntervalSinceNow:2.0]];

        [pool drain];
    }
}

/* puts you in a position to be able, whenever you want to issue things like: */
[self
        performSelector:@selector(myAsynchronousAction)
        onThread:myThread
        withObject:nil
        waitUntilDone:NO];

因此,您在那里所做的是为自己设置一个类似GCD串行调度队列的东西。

如果原始海报错误地认为他/她需要始终在
NSThread
中运行
nsrunlop
,请让我提一下:

如果您只想在其他线程中运行另一个方法,只需执行以下操作:

-(void)someMethod:(NSObject*)someObjectToBePassedIn
{
   the thing you'd like to do in a background thread
}
然后呢

NSThread*thread=[NSThread detachNewThreadSelector:@selector(someMethod:) 
                                         toTarget:self withObject:someObject];

没有第三步

对于线程,我主要使用“grand central dispatch”,其次,GCD非常简单,在线程方面非常强大!我也是。由于我使用three20网络层作为我的DAL的基础,所以这个问题主要就要出现了。它使用NSTimer在某个时间点添加延迟,如果您在GCD中生成了后台任务,则生成的线程中没有运行循环。NSTimer在(本例中不存在)运行循环中调度自身。因此,线程将在没有通知的情况下结束线程,并且您将永远无法从TTURLRequest获得答案。这就是为什么我想为网络生成一个后台线程,或者如果该线程仅使用一个方法运行,我想NSObject的
performSelectorInBackground:…
也将是一个选项?您确定默认情况下NSThread具有nsrunlop吗?正如我在对我的OP的评论中提到的,如果我在GCD中生成了一个任务,并且它计划了一个NSTimer,那么线程将结束,计时器将永远不会启动。由于NSTimer在runloop中调度自身,因此需要显式调用runloop。所以我认为“GCD线程”不使用运行循环。我看到的堆栈痕迹似乎支持这一观点。不,你说得很对——我在阅读苹果的文档时漏掉了“按需”这几个重要的词。正确的解释是,NSThreads本质上提供nsrunlop,但它可能是延迟分配的-请参阅我将自动释放池的init移出while循环,以避免内存泄漏:)@Tomen我不确定您的更改是否正确;自动释放池是一种特殊情况,因为在引用计数环境中,
drain
release
同义,但在垃圾收集下也允许使用,充当垃圾收集器的提示。所以我把它改回来了,但是如果我遗漏了什么,请说出来。哦,对不起,我误解了这个方法。你的论点是正确的。