Potential leak of an object allocated for Activity indicator window - iphone

I use ActivityIndicatorC class in the application delegate file and alloc object for it but here i get memory leak,
self.ActIndicator=[[ActivityIndicatorC alloc] initwithWindow:window];
I release ActIndicator this object in the dealloc section but till i am get same potential leak for the above mention code.
Any solution any one can suggest for it.

the object is retained twice. When using self.ActIndicator = you invoke the setter, which the compiler created for you by using the #property(retain,...) you put in your interface.
self.ActIndicator=[[ActivityIndicatorC alloc] initwithWindow:window];
^ retainCount + 1 ^^^^^ and +1 because of this.
you could write
self.ActIndicator = [[[ActivityIndicatorC alloc] initwithWindow:window] autorelease];
or
ActIndicator = [[ActivityIndicatorC alloc] initwithWindow:window];
And you should change the name to actIndicator or (even better) activityIndicator. Only class names should start with a capital letter.

if ActIndicator is set to retain property . then there is leak in .h file make
#property(nonatominc ,retain) to #property(nonatominc ,assign) or
ActivityIndicatorC *theActivity= [[ActivityIndicatorC alloc] initwithWindow:window];
self.ActIndicator=theActivity;
[theActivity release];

You'll have to manually release objects created with alloc-init. So you should write a [ActIndicator release]; or just autorelease it.

Related

Allocating a property

Working on someone else's code. Came across a piece of code while analyzing the project
self.groupPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,260,320,216)];
self.groupPicker.delegate = self;
self.groupPicker.showsSelectionIndicator = YES;
[self.view addSubview:self.groupPicker];
Where groupPicker is a UIPicker property. When analyzing the project I encountered a potential leak warning in this case. I have also noticed that the groupPicker property is not being released in the dealloc method. Nor is _groupPicker released anywhere in the project. What should be done in this case?
Should I remove the UIPicker property and just declare a UIPicker variable instead.
Should I just release groupPicker like [_groupPicker release];
What would be the retain count of groupPicker as it is retained once in the .h file and again being allocated as shown in the above piece of code.
1) No, it is perfectly fine to have the property, the problem is that it is being over retained. When you alloc/init the retain count is 1, then you use the retained property which increases the retain count again. The retain count is now 2 and assuming you release the object in dealloc, you end up with a retain count of 1, i.e. a leaked object.
There are many ways you can handle the problem. I think the best way is to autorelease the object on initialization. Like so
self.groupPicker = [[[UIPickerView alloc] initWithFrame:CGRectMake(0,260,320,216)] autorelease];
2) Anything you retain should be released in dealloc, so in dealloc you should
- (void)dealloc {
[_groupPicker release];
[super dealloc];
}
Watch out! When you set a property like
self.property1 = x;
and the property1 is declared as retain, the previous object in the property1 is released and the new object (x) is retained. This is why doing this:
self.property1 = [[x alloc] init];
when property1 is declared as retain, will retain x twice. (one for init, one for setting the property)
The correct way is declaring the object, setting to the property and then releasing
object x = [[class alloc] init];
self.property1 = x;
[x release];
This way, you give the "responsability" of releasing the object x to the property holder.
While using ARC for iOS5+ applications should be preferred, if you don't want to do that just use autorelease after init method.
You should use ARC (Automatic Reference Counting)
to do so got to edit>refactor>convert to objective c ARC
Either assign the UIPickerView to _groupPicker (or whatever the instance variable is named), or use an autorelease on the value as you assign it.
(The problem is that assigning to a retained property causes a retain, and there's already a retain on the object from the alloc.)

How to release an object in a forin loop?

I'm new to cocoa / objective-c and i'm struggeling with the releases of my objects. I have the following code:
gastroCategoryList = [[NSMutableArray alloc] init];
for (NSDictionary *gastrocategory in gastrocategories) {
NSString *oid = [gastrocategory objectForKey:#"id"];
GastroCategory *gc = [[GastroCategory alloc] initWithId:[oid intValue] name:[gastrocategory objectForKey:#"name"]];
[gastroCategoryList addObject:gc];
}
The analyzer shows me that the "gastrocategory" defined in the for is a potential memory leak. But i'm not sure if i can release this at the end of the for loop?
Also at the following code:
- (NSArray *)eventsForStage:(int)stageId {
NSMutableArray *result = [[NSMutableArray alloc] init];
for (Event *e in eventList) {
if ([e stageId] == stageId) {
[result addObject:e];
}
}
return result;
}
The Analyzer tells me that my "result" is a potential leak. But where should I release this?
Is there also a simple rule to memorize when i should use assign, copy, retain etc. at the #property ?
Another problem:
- (IBAction)showHungryView:(id)sender {
GastroCategoriesView *gastroCategoriesView = [[GastroCategoriesView alloc] initWithNibName:#"GastroCategoriesView" bundle:nil];
[gastroCategoriesView setDataManager:dataManager];
UIView *currentView = [self view];
UIView *window = [currentView superview];
UIView *gastroView = [gastroCategoriesView view];
[window addSubview:gastroView];
CGRect pageFrame = currentView.frame;
CGFloat pageWidth = pageFrame.size.width;
gastroView.frame = CGRectOffset(pageFrame,pageWidth,0);
[UIView beginAnimations:nil context:NULL];
currentView.frame = CGRectOffset(pageFrame,-pageWidth,0);
gastroView.frame = pageFrame;
[UIView commitAnimations];
//[gastroCategoriesView release];
}
I don't get it, the "gastroCategoriesView" is a potential leak. I tried to release it at the end or with autorelease but neither works fine. Everytime I call the method my app is terminating. Thank you very much again!
In your loop, release each gc after adding it to the list since you won't need it in your loop scope anymore:
gastroCategoryList = [[NSMutableArray alloc] init];
for (NSDictionary *gastrocategory in gastrocategories) {
NSString *oid = [gastrocategory objectForKey:#"id"];
GastroCategory *gc = [[GastroCategory alloc] initWithId:[oid intValue] name:[gastrocategory objectForKey:#"name"]];
[gastroCategoryList addObject:gc];
[gc release];
}
In your method, declare result to be autoreleased to absolve ownership of it from your method:
NSMutableArray *result = [[[NSMutableArray alloc] init] autorelease];
// An alternative to the above, produces an empty autoreleased array
NSMutableArray *result = [NSMutableArray array];
EDIT: in your third issue, you can't release your view controller because its view is being used by the window. Setting it to autorelease also causes the same fate, only delayed.
You'll have to retain your GastroCategoriesView controller somewhere, e.g. in an instance variable of your app delegate.
BoltClock's answer is spot-on as to the first part of your question. I'll try to tackle the rest.
Assign is for simple, non-object types such as int, double, or struct. It generates a setter that does a plain old assignment, as in "foo = newFoo". Copy & retain will, as their names imply, either make a copy of the new value ("foo = [newFoo copy]") or retain it ("foo = [newFoo retain]"). In both cases, the setter will release the old value as appropriate.
So the question is, when to copy and when to retain. The answer is... it depends. How does your class use the new value? Will your class break if some other code modifies the incoming object? Say, for example, you have an NSString* property imaginatively named "theString." Other code can assign an NSMutableString instance to theString - that's legal, because it's an NSString subclass. But that other code might also keep its own reference to the mutable string object, and change its value - is your code prepared to deal with that possibility? If not, it should make its own copy, which the other code can't change.
On the other hand, if your own code makes no assumptions about whether theString might have been changed, and works just as well whether or not it was, then you'd save memory by retaining the incoming object instead of unnecessarily making a copy of it.
Basically, the rule, which is unfortunately not so simple sometimes, is to think carefully about whether your own code needs its own private copy, or can correctly deal with a shared object whose value might be changed by other code.
The reason you can release gc after it is added to the gastroCategoryList is that when an object is added to an array, the array retains that object. So, even though you release your gc, it will still be around; retained by the gastroCategoryList.
When you are returning a newly created object from a method, you need to call autorelease. This will cause the object to be released only after the runtime leaves the scope of the calling method, thereby giving the calling method a chance to do something with the returned value.
Note that if your method starts with the word copy or new, then you should not autorelease your object; you should leave it for the calling method to release.
As for copy vs retain vs assign... as a general rule, copy objects that have a mutable version, such as NSArray, NSSet, NSDictionary, and NSString. This will ensure that the object you have a pointer to is not mutable when you don't want it to be.
Otherwise, use retain whenever you want your class to be ensured that an object is still in memory. This will apply to almost every object except for objects that are considered parents of your object, in which case you would use assign. (See the section on retain cycles here).
Also note that you have to use assign for non-object types such as int.
Read through the Memory Management Programming Guide a bit; it's quite helpful.

Should I retain or assign the viewcontroller in this case?

Interface
#property (nonatomic, retain) PracticalSignsMainViewController *practicalVC;
Implementation
if (self.practicalVC == nil) {
PracticalSignsMainViewController *vc = [[PracticalSignsMainViewController alloc] init];
self.practicalVC = vc;
[vc release];
}
I only want to make one viewcontroller object in this case and change the data that it acts upon. However is it correct to retain or assign this viewcontroller (and why so)? It is used in a navigation-hierachy.
Thanks.
Retain. Typically you want object properties to be retained, and primitive properties to be assigned. The answer here is really good: Use of properties for primitive types
If you're planning to cache a view controller that's used in a navigation, you would need to retain it. The reason is that while the navigation controller retains it temporarily, once the user hits the back button the navigation controller will send the view controller a release message. If you haven't retained the view controller anywhere else at that point it will be deallocated.
If you're creating a new instance each time, that would be fine, but obviously that would destroy a cached instance if the property uses assign semantics.
Firstly, your code is right, but it can be more simple.
If you did the following synthesize,
#synthesize practicalVC; // synthesize release the existing reference if has
the following code is same as your code.
self.practicalVC = [[[PracticalSignsMainViewController alloc] init] autorelease];
As you mentioned, if your app does not need many access to the view controller, you need not to have view controller's instance separately.
============== Modified ====================
And I modified my answer after seeing answers of #6NSString #Abizern.
Regarding autorelease and coding style.
1. autorelease,
#6NSString said that "it uses autorelease which many avoid unless returning an newly alloced object."
But even if you use "autorelease" in return statement, the retain count of the returned object is not immediately decreased. It will be decreased at an appropriate time.
So If we want to decrease the retaincount explicitly and immediately, we should use paired "release".
-(NSObject*)testAuto {
return [[[NSObject alloc] init] autorelease];
}
...
self.anObj = [self testAuto];
// the retainCount of anObj is 2
..
-(void)testAuto {
self.anObj = [[[NSObject alloc] init] autorelease];
}
...
[self testAuto];
// the retainCount of anObj is also 2
..
-(void)testAuto {
self.anObj = [[[NSObject alloc] init] autorelease];
[self.anObj release]; // Yes, yes, you may say this code does not look good. :)
}
...
[self testAuto]
// the retainCount of anObj is 1
...
As you see, (I naturally tested above code again) "autorelease"s both in return statement and in alloc statement are almost same. And if you want to manage retain count harder, we should use "release".
I think "autorelease" in alloc statement is better than one in return statement because "autorelease" in return can be omitted. :)
2. Coding style,
As the end of "1. autorelease", I think, autorelease in alloc statement would be more safe to avoid missing release.

IPhone memory management

I am a bit lost with the memory management. I've read that you should release whenever you alloc. But when you get an instance without the alloc, you shouldnt release.
What about this situation, just need to know If I was coding correctly. I'm still new on iphone dev.
I have a class CustomerRepository it has a method
- (MSMutableArray *) GetAllCustomers() {
MSMutableArray *customers = [[MSMutableArray alloc] init];
Customer *cust1 = [[Customer alloc] init];
cust1.name = #"John";
Customer *cust2 = [[Customer alloc] init];
cust2.name = #"Tony";
[customers addOjbect:cust1];
[customers addOjbect:cust2];
[cust1 release];
[cust2 release];
return customers;
}
Then I have a UIViewController
- (void) LoadCustomers() {
CustomerRepository *repo = [[CustomerRepository alloc] init];
MSMutableArray *customers = [repo GetAllCustomers];
// Iterate through all customers and do something
[repo release];
}
So in this scenario ... the MSMutableArray will never be release? Where should it be release?
If you alloc an object in a function that you need to return from the function then you can't release it inside the function. The correct way to do this is to autorelease the object.
MSMutableArray *customers = [[MSMutableArray alloc] init];
// ..... do work
return [customers autorelease];
This is the approach taken by the connivence constructors like
[NSString stringWithString:#"test"];
This method will return you an autoreleased string so that you don't need to release it.
And if you don't do this then you should name your function accordingly that the caller knows that it owns the returned object and thus needed to be released. These are conventions, not a rule imposed by the compiler or run-time environment but following convention is extremely important, specially when multiple people are involved in the project.
Whenever you create and return an object from a method or function, that object should be autoreleased. The exceptions are when the method starts with Create or New (or Alloc, obviously), or when the object is being cached within the method.
The other answers which suggest releasing it in LoadCustomers are incorrect, because GetAllCustomers does not imply a transfer of ownership like CreateCustomersArray or NewCustomersArray would. However, you can't release the object in GetAllCustomers either because then the object would be deallocated before returning it. The solution is autorelease.
The customers array should be released after you are done iterating it. You delegated the creation of the array to your repo object but your LoadCustomers method owns the array.
Another approach would be to have your CustomerRepository expose an allCustomers property. You could lazily initialize the array in your getter and then release the array when the CustomerRepository is released. That would keep your calls to alloc and release in the same object.
it should be released in your view controller, LoadCustomers() since you are allocing it in the method you are calling, it is still owned by YOU.

Unnecessary temporary variables when setting property values?

I'm following a book on iPhone development and there is a particular pattern I keep seeing in the example code that doesn't make much sense to me. Whenever a property is set they first assign a pointer to the new value for the property, then set the property to the pointer, then release the pointer. Example:
Interface:
#interface DoubleComponentPickerViewController : UIViewController {
NSArray *breadTypes;
}
#property(nonatomic, retain) NSArray *breadTypes;
#end
Class method:
- (void)viewDidLoad {
NSArray *breadArray = [[NSArray alloc] initWithObjects:#"White", #"Whole Wheat", #"Rye", #"Sourdough", #"Seven Grain", nil];
self.breadTypes = breadArray;
[breadArray release];
}
Is there any reason to do this instead of just doing the following?
- (void)viewDidLoad {
self.breadTypes = [[NSArray alloc] initWithObjects:#"White", #"Whole Wheat", #"Rye", #"Sourdough", #"Seven Grain", nil];
}
Thanks for the light that will no doubt be shed :)
Let me try and explain it in a different way.
A method that has alloc, copy or new in its name will allocate memory for an object, and gives ownership of that object to the caller, and it is the caller's responsibility to release that memory.
In your viewDidLoad method, you call a method that gives you ownership of an object. It is your method's responsibility to release it. However, before you do that, you want to do something with it - after all, that's why you alloc'ed it, not to just release it, but to do something useful with it.
Regardless of what it is that you want to do with it, you have to release it (or autorelease it*). In this case your use of the object is to pass it to self.breadTypes. self.breadTypes may not look like a method, but it is (it is a setter). You pass it breadArray. It does what it needs to with it. It might retain it for use later, or it might copy some info out of it, or make a copy of the entire thing. Your viewDidLoad doesn't really care. It assumes that self.breadTypes does what it needs to and when it returns, it doesn't care what you do with breadArray.
And what you do with it, is what you have to do with anything that you own - release (or autorelease* it).
That's why you have to use the temp variable, breadArray. You can't quite release the results from alloc on the same line, since the object would get released before self.breadTypes can have at it:
self.breadTypes = [[[NSArray alloc] initWithObjects:#"White", ..., nil] release];
Thus you are forced to assign to a temp variable, pass it to self.breadTypes, and then release the object that is saved in breadArray.
Now, you could try to do it this way so you don't use a temp variable:
- (void)viewDidLoad {
self.breadTypes = [[NSArray alloc] initWithObjects:#"White", #..., nil];
[self.breadTypes release];
}
but that is not very efficient since you are calling yet another method (self.breadTypes as a getter) that you didn't really need to if you have just stored the value in a temp variable.
*Now, as a responder said, you could use autorelease for an alternative version:
- (void)viewDidLoad {
self.breadTypes = [[[NSArray alloc] initWithObjects:#"White", ..., nil]
autorelease];
}
Apple urges us to think twice about whether we want to use autorelease vs. release. Autorelease may not be the best choice for every situation. I personally like to clean up after myself as soon as I possibly can, and not use autorelease needlessly. Autoreleased objects get released at the end of the execution of the run loop, for example soon after viewDidLoad returns. You should read up a bit more about autorelease (and memory management on the iPhone which is slightly different than MacOS X Cocoa), as I am oversimplifying it all.
BTW: If you retain an object, you are assuming ownership of it, and you will have the same responsibility again, to release it after you are done with it.
Yes. Those methods are alloc'ing the variables so they must be released. The fact that the property has a retain attribute means that when you say #synthesize breadTypes; the compiler is actually generating a setBreadTypes that properly releases the current breadType member and retains the new one. Thus your function must not retain the variable it alloc'ed.
You could, however write:
- (void)viewDidLoad {
self.breadTypes = [[[NSArray alloc] initWithObjects:#"White",
#"Whole Wheat", #"Rye", #"Sourdough",
#"Seven Grain", nil]
autorelease];
}
You'll want to brush up on Cocoa Memory Management