1

I'm probably overthinking this.

// Inside some method...
NSThread *thread = [[NSThread alloc] initWithTarget:functionWrapper selector:@selector(run) object:nil];
[thread start];

Calling [thread release] after this: A. Avoids a memory leak and is necessary or... B. Will break things.

The answer to this question suggests that the thread will release itself when it finished executing, but where is that behavior documented?

Community
  • 1
  • 1
Ben Flynn
  • 18,524
  • 20
  • 97
  • 142
  • It is here https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html – onmyway133 Mar 07 '13 at 12:09

2 Answers2

5

Yes you will have to release it some time later, either through autorelease or release.

However, you don't really need to init your own thread in the first place, objective-c has plenty of ways for you to implement threading without allocing a new thread yourself, like

[self performSelectorInBackground:@selector(yourMethod) withObject:nil];

There are also NSOperations that allow you to queue up your tasks as well.

futureelite7
  • 11,462
  • 10
  • 53
  • 87
  • Let me look to see if I could do that. Looking at someone else's code and they are jumping through some hoops that might not be necessary. – Ben Flynn Jul 17 '12 at 01:20
  • Thanks for the backgrounding suggestion, it worked great! If I could start from scratch we might be using GCD. – Ben Flynn Jul 17 '12 at 01:30
2

As a general rule: If you call alloc, new, or copy on an object, you have to release it.

Once the lifecycle of that thread is complete (or in your dealloc function), call [thread release].

The difference with the answer you linked to, you'll see he had autorelease at the end of the string (autoreleasing is the instance where the rule above doesn't apply, in those cases the object will be automatically released at the end of the current main run loop so that it is alive for the entire current scope).

andycam
  • 1,682
  • 14
  • 27
  • I thought autoreleasing just keeps the memory around until the next time execution processes the autorelease pool. It doesn't actually do reference counting right -- that would be garbage collection. – Ben Flynn Jul 17 '12 at 01:12
  • 2
    @BenFlynn Autoreleasing means that the object's retain count will be decremented by 1 in the next drain of the autorelease pool it is in. If it is not retained by anything else before this happens, it will be deallocated. It has no relation on setting the object to nil as stated above. Autoreleasing is the same as releasing in terms of the bold lettered rule in the answer (it is just a delayed release). – borrrden Jul 17 '12 at 01:45
  • 1
    @BenFlynn Correct, and as borrrden elaborated, I was mistaken as to the nature of autoreleasepool draining. Edited my answer in the interests of not spreading misinformation! – andycam Jul 17 '12 at 02:01