This post covers some tips for novice programmers that can be helpful if you are not using ARC and are managing the memory yourself. For this post, I assume, that you are familiar with memory management and related methods ( retain, alloc, release ... etc ). So lets begin:
[[NSMenuItem alloc]initWithTitle:[[NSString alloc] initWithString:@"xyz"] action:@selector(selector:) keyEquivalent:@""];
Using Anonymous Objects
It is pretty common for the developers to use anonymous objects and a newbie programmer can unknowingly leak memory while using them as shown in the example below:
[[NSMenuItem alloc]initWithTitle:[[NSString alloc] initWithString:@"xyz"] action:@selector(selector:) keyEquivalent:@""];
In the code above, we are trying to create a new menu item, which requires a NSString as one of its arguments and we are creating the string there and then. As we can see that we are using alloc to create the
string, the retain count of this string is being incremented from 0 to 1. But we wont be able to release it because we have no reference to it. Hence, this statement is leaking memory.
string, the retain count of this string is being incremented from 0 to 1. But we wont be able to release it because we have no reference to it. Hence, this statement is leaking memory.
So, lets rectify this statement:
[[NSMenuItem alloc]initWithTitle:[[[NSString alloc] initWithString:@"xyz"]autorelease] action:@selector(selector:) keyEquivalent:@""];
By using autorelease while creating a string, the autorelease pool will make sure that this string won't be released for a minimum of 1 event loop cycle (so we can use it without worrying) and after that, autorelease pool will also make sure that this string is released in the near future.
Using Notifications
Although using notifications is not directly related to memory management, but I feel it is worth mentioning.
When you register to receive a notification, the notification center creates a weak reference to your object. Now suppose, you have registered an object as observer with the notification center to receive a notification and at some point of time, the observer has been released and ceases to exist, the notification center will be unaware of this release as it holds only a weak reference of the object. So, the notification center will keep on sending notifications to that object even if does not exist. So, we should notify the notification center that the object no longer exists.
So, ideally when you register for a notification, you must un-register for that notification in -(void)dealloc; or at some other appropriate place.
No comments:
Post a Comment