0

In my code for search controller I am using NSthread. For every character we enter in the search bar a new thread is created very next the thread is started. How do we release these NSThreads which are causing memory leaks?

Here is where my NSThreads are created:

if (searchString.length > 1) {
    self.searchThread = [[[NSThread alloc] initWithTarget:self selector:@selector(filterContentForSearchTextInBackgroundThread:) object:searchString] autorelease];
    [self.searchThread start];

}
Tim
  • 14,999
  • 1
  • 45
  • 68
Vijay
  • 71
  • 1
  • 2
  • 11
  • Here are two relevant questions you may be interested in: http://stackoverflow.com/questions/11514739/should-i-release-the-nsthread-i-create and http://stackoverflow.com/questions/7749326/please-explain-me-about-this-leak/7749478 – Calvin Jul 17 '12 at 17:59

1 Answers1

4

Answer: self.searchThread = nil; will release the thread when it is done executing.

Longer answer; you really really don't want to spawn a thread on every keystroke. If you are going to use threads at all, you should have ONE thread that processes keystrokes and you should tell that thread about the keystrokes as they happen.

Which means you are probably going to need some kind of "cancel the current query and start a new one" mechanism, too.

bbum
  • 162,346
  • 23
  • 271
  • 359
  • It seems like setting `self.searchThread = nil` is a meaningless gesture unless garbage collection is enabled. The thread is being autoreleased already; that should be enough. – Calvin Jul 17 '12 at 16:06
  • You can't balance the retain of a property with the autorelease of object creation; that'll lead to Very Bad Things (as written, OP's code is +1 RC (alloc), -1 RC(delayed), +1 RC (assignment). Thus, yes, unless ARC is enabled you either need to set the property to nil or release the ivar directly to balance the retain on assignment. – bbum Jul 17 '12 at 16:49
  • Assignment operations in Objective-C do not modify the reference count. Looking at the code, I see +1 RC (alloc) and -1 RC (delayed by autorelease). – Calvin Jul 17 '12 at 17:36
  • I'm assuming `searchThread` is defined as `@property(retain)`. – bbum Jul 17 '12 at 18:05