Blu*_*hin 12 cocoa multithreading memory-leaks memory-management
我有一种方法可以将文件保存到互联网上,它可以工作但速度很慢.然后我想让用户界面更加流畅,所以我创建了一个NSThread来处理缓慢的任务.
我看到一个错误列表,如:
_NSAutoreleaseNoPool(): Object 0x18a140 of class NSCFString autoreleased with no pool in place - just leaking
Run Code Online (Sandbox Code Playgroud)
没有NSThread,我称之为:
[self save:self.savedImg];
Run Code Online (Sandbox Code Playgroud)
我使用以下内容使用NSThread来调用方法:
NSThread* thread1 = [[NSThread alloc] initWithTarget:self
selector:@selector(save:)
object:self.savedImg];
[thread1 start];
Run Code Online (Sandbox Code Playgroud)
谢谢.
ker*_*emk 15
首先,您要为保存代码创建一个新线程,然后异步使用NSUrlConnection.NSUrlConnection在它自己的实现中也会分拆另一个线程并在你新创建的线程上回调,这主要不是你想要做的事情.我假设您只是想确保在保存时UI不会阻塞...
NSUrlConnection也有同步版本,它将阻塞你的线程,如果你想启动你自己的线程做事情,最好使用它.签名是
+ sendSynchronousRequest:returningResponse:error:
Run Code Online (Sandbox Code Playgroud)
然后,当您收到响应时,您可以回调您的UI线程.下面的东西应该工作:
- (void) beginSaving {
// This is your UI thread. Call this API from your UI.
// Below spins of another thread for the selector "save"
[NSThread detachNewThreadSelector:@selector(save:) toTarget:self withObject:nil];
}
- (void) save {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// ... calculate your post request...
// Initialize your NSUrlResponse and NSError
NSUrlConnection *conn = [NSUrlConnection sendSyncronousRequest:postRequest:&response error:&error];
// Above statement blocks until you get the response, but you are in another thread so you
// are not blocking UI.
// I am assuming you have a delegate with selector saveCommitted to be called back on the
// UI thread.
if ( [delegate_ respondsToSelector:@selector(saveCommitted)] ) {
// Make sure you are calling back your UI on the UI thread as below:
[delegate_ performSelectorOnMainThread:@selector(saveCommitted) withObject:nil waitUntilDone:NO];
}
[pool release];
}
Run Code Online (Sandbox Code Playgroud)
您需要主要为线程创建自动释放池.尝试将保存方法更改为:
- (void) save:(id)arg {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//Existing code
[pool drain];
}
Run Code Online (Sandbox Code Playgroud)
你不会认为上述内容不会在NSAutoreleasePool上调用release.这是一个特例.对于NSAutoreleasePool,相当于在没有GC的情况下运行时释放,并转换为收集器的提示,可能是运行集合的好点.