Question

After running my thread for a while, Instruments shows that __NSDate has steadily incementing its # living value.

My conclusion is that this tread does not dealocate objects. This line, however, causes compilation error NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

How can I force this thread to retain all its objects or how shall I create a proper thread with working 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 ...

}
Was it helpful?

Solution

The autoreleased objects are probably the reason for the increasing memory usage, but you cannot use NSAutoreleasePool with ARC. Replace

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// ...
[pool drain];

with

@autoreleasepool {
    // ...
}

Update: You actually need two autorelease pools in your case. First of all, the Threading Programming Guide states:

If your application uses the managed memory model, creating an autorelease pool should be the first thing you do in your thread entry routine. Similarly, destroying this autorelease pool should be the last thing you do in your thread. This pool ensures that autoreleased objects are caught, although it does not release them until the thread itself exits.

And the last sentence gives the clue why you need another autorelease pool: Otherwise all autoreleased objects created in the long-running loop would only be released when the thread exits. So you have

- (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 ...
    }
}

OTHER TIPS

- (void)myThreadMainRoutine {
    @autoreleasepool {
       // 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 ...

   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top