Question

Just starting out with Objective-C after spending years in Python.. still trying to wrap my head around some concepts.. I can't seem to figure this out but every time I either increment up or deduct from myCount it retains the older variable in memory. I am using ARC so shouldn't it autorelease? I have a feeling it has to do with self.varOfMyCount = [NSString stringWithFormat:@"%d", myCount];

Header:

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate>
{
    IBOutlet NSMenu *statusMenu;
    NSStatusItem *statusItem;
}
- (IBAction)itemOne:(id)sender;
- (IBAction)itemTwo:(id)sender;
- (IBAction)itemThree:(id)sender;



@property (assign) IBOutlet NSWindow *window;
@property (nonatomic, copy) NSString *varOfMyCount;

@end

int myCount = 0;

Implementation:

#import "AppDelegate.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength ];
    [statusItem setMenu:statusMenu];
    [statusItem setTitle:@"Status"];
    [statusItem setHighlightMode:YES];
}

- (IBAction)itemOne:(id)sender {
    myCount++;
    self.varOfMyCount = [NSString stringWithFormat:@"%d", myCount];
    NSLog(@"%@",self.varOfMyCount);
    [statusItem setTitle:self.varOfMyCount];
}

- (IBAction)itemTwo:(id)sender {
    myCount = myCount-1;
    self.varOfMyCount = [NSString stringWithFormat:@"%d", myCount];
    NSLog(@"%@",self.varOfMyCount);
    [statusItem setTitle:self.varOfMyCount];

}

- (IBAction)itemThree:(id)sender {
    NSLog(@"Quit.");
    [[NSApplication sharedApplication] terminate:nil];
}
@end
Was it helpful?

Solution

From your images, it doesn't really look like there is a problem. In order for your app to run it does need to use memory. Depending on what you do it will use different amounts.

Using [NSString stringWithFormat:@"%d", myCount]; requires more than you might think because you are asking the system to parse your format string and inject parameters into it. Parsing and scanning a string isn't a trivial operation.

In a number of cases when memory is allocated for a task it isn't released. This is usually the case when it's expensive to create (like the scanning structure, or parts of it) or is likely to be used repeatedly.

You should be worried if the memory grows bigger each time you do the same activity and return to your 'transient' state. Consider running multiple iterations of your button push and, between each push, take a heap shot. If each heap shot (apart from the first and last) are empty (or very close to it) then everything's good. If not, it will show exactly what isn't being released.

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