Search code examples
iosobjective-cj2objc

Why does passing a static reference to a class consume memory?


instruments screen capture

I'm having difficulty understanding why this is consuming memory.

I have tried;

  1. Allowing more time for ARC to clean up
  2. Creating a __weak copy of globals to pass
  3. Looked at using __bridge or __bridge_transfer but I don't believe this is appropriate.
  4. Making globals public and referencing it directly (works, but impractical)

This iOS Objective c thread is translated via j2objc 0.9.3 from a Java App.

@implementation Comms_StatusThread

- (void)run {
while (true) {

    // Consumes memeory at aproximately 100k per 5 min
    [S globals];

    @try {
        [JavaLangThread sleepWithLong:10];
    }
    @catch (JavaLangInterruptedException *e) {
    }
}

This translated static singleton stores "globals" to be accessed from anywhere in the app (the real code stores many more classes & callbacks).

@implementation S

Globals * S_globals__ = nil;

+ (Globals *)globals {
    {
        if (S_globals__ == nil) S_globals__ = [[Globals alloc] init];
        return S_globals__;
    }
}

@end

Any help appreciated. I'm new to objective-c and ARC. I've read a fair amount on ARC, but still don't understand the cause of this memory consumption.


Thanks to Student T I tried the following.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(test:) userInfo:nil repeats:YES];
    return YES;
}

-(void) test: (NSObject*) o {
    [S comms];
    [S globals];
}

This does not consume memory and I was planning to do this however tball's new answer (use j2objc @AutoreleasePool) is clearly the best option, so I'll start there.

Thank you so much for all your answers!


Solution

  • Assuming you're compiling using ARC, because if you aren't, the whole conversion is meaningless. Your experiment wouldn't work because you put the code in a infinite loop. You tried to sleep the thread but it wouldn't work because you were also stopping the main running thread at the same time. You need to give the main run-loop a chance to run in the 10s duration.