mic*_*ael 0 multithreading objective-c nsthread ios automatic-ref-counting
在运行我的线程一段时间后,Instruments表明__NSDate已经稳定地修改了它的#vide值.
我的结论是,这个步骤不会处理对象.但是,这一行导致编译错误NSAutoreleasePool*pool = [[NSAutoreleasePool alloc] init];
如何强制此线程保留其所有对象,或者如何使用工作ARC创建正确的线程.
- (void) start {
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(myThreadMainRoutine)
object:nil];
[myThread start]; // Actually create the thread
}
- (void)myThreadMainRoutine {
// stuff inits here ...
// Do thread work here.
while (_live) {
// do some stuff ...
[runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
[NSThread sleepForTimeInterval:0.05f];
}
// clean stuff here ...
}
Run Code Online (Sandbox Code Playgroud)
自动释放的对象可能是内存使用量增加的原因,但您无法使用NSAutoreleasePoolARC.更换
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// ...
[pool drain];
Run Code Online (Sandbox Code Playgroud)
同
@autoreleasepool {
// ...
}
Run Code Online (Sandbox Code Playgroud)
更新:您实际上需要两个自动释放池.首先, 线程编程指南指出:
如果您的应用程序使用托管内存模型,那么创建自动释放池应该是您在线程入口例程中首先要做的事情.同样,销毁这个自动释放池应该是你在线程中做的最后一件事.此池确保捕获自动释放的对象,但在线程本身退出之前不会释放它们.
最后一句话给出了为什么你需要另一个自动释放池的线索:否则在长时间运行的循环中创建的所有自动释放的对象只会在线程退出时释放.所以你有了
- (void)myThreadMainRoutine {
@autoreleasepool {
// stuff inits here ...
while (_live) {
@autoreleasepool {
// do some stuff ...
[runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]];
[NSThread sleepForTimeInterval:0.05f];
}
}
// clean stuff here ...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
781 次 |
| 最近记录: |