#interface Foo : NSObject
#property (nonatomic, retain) Bar * bar;
#end
#implementation Foo
#synthesize bar = _bar;
- init {
self = [super init];
if (self) {
_bar = [[Bar alloc] init];
// Or
_bar = [[[Bar alloc] init] autorelease];
}
return self;
}
- (void)dealloc {
[_bar release];
[super dealloc];
}
#end
When I run the analyzer, both
_bar = [[Bar alloc] init];
and
_bar = [[[Bar alloc] init] autorelease];
are fine.
Which one I should use?
You should use the first. It creates a retained object, whereas the second "autoreleases" that retain.
The important consideration is that you're assigning it to instance variable _bar. If you were, instead, assigning it to property self.bar, then the retain directive in the property declaration would cause the object to be retained, so assigning an autoreleased value would be appropriate. But since you're assigning to the "bare" instance variable instead, you need to handle the retain yourself, so you need the first form.
PS: I'm a bit surprised that the analyzer doesn't complain about the second version.
PPS: It should be noted that the choice here is highly context dependent. But you included enough context (the property definition) to make the choice. Without seeing the property definition (or other info, in the case of a non-property) it would be hard to say.
The autorelease version is not correct and may cause crashes in some situations—your first line results in _bar having a retain count of 1, and thus sticking around until it's released in -dealloc when you no longer need it.
The second line, however, releases the object soon-ish (specifically, at the end of the run loop), and thus could cause it to disappear when you still need it.
Read Apple's Guide on Memory Management for more information.
Related
Say I have two properties defined as such:
#property (nonatomic, strong) UITableView *parentTableView;
#property (nonatomic, strong) NSMutableArray *headersArray;
and a method:
-(void)prepareTags;
and say I have an init method like this:
-(id)initWithParentTableView:(UITableView*)parentTable
{
if(self = [super init])
{
//1
NSMutableArray *array = [[NSMutableArray alloc] init];
headersArray = array;
//2
self.parentTableView = parentTable;
//3
[self prepareTags];
}
return self;
}
Is this the correct way to set up the headers array in an init method?
Am I allowed to call self.parentTableView from the init method?
Am I allowed to call a method from the init method (in this case, the prepareTags method calls self too. Will self be ready to use, even though the init method hasn't returned yet?
Respectively (I'd use list formatting but I can't make it work with blockquotes...!):
Is this the correct way to set up the headers array in an init method?
Yes, but there's no point having the array variable, you might as well just do: headersArray = [[NSMutableArray alloc] init];
Am I allowed to call self.parentTableView from the init method?
No, to quote the Apple docs on Practical Memory Management:
Don’t Use Accessor Methods in Initializer Methods and dealloc
. You should access the ivar directly (as you do with headersArray)
Am I allowed to call a method from the init method (in this case, the prepareTags method calls self too. Will self be ready to use, even though the init method hasn't returned yet?
Yes. Just be very careful (your object may not have been fully initialised, it shouldn't use accessor methods so as to comply with the previous restriction, et cetera)
There's no need to use a local variable here:
NSMutableArray *array = [[NSMutableArray alloc] init];
headersArray = array;
Just assign to the instance variable directly:
headersArray = [[NSMutableArray alloc] init];
Am I allowed to call self.parentTableView from the init method?
Yes, although some people might consider that poor design. Consider the fact that properties sometimes have non-obvious complex setter methods that look at other instance variables. Is it wise to do this when your object hasn't been fully initialised?
Am I allowed to call a method from the init method?
Same as above. So long as you aren't relying on anything you haven't initialised yet, it's fine.
The code looks pretty good. Just a couple notes...
-(id)initWithParentTableView:(UITableView*)parentTable
{
// avoid compiler warning about the assignment and the condition in the same statement
self = [super init];
if(self)
{
//1
// no need for the extra stack variable
self.headersArray = [[NSMutableArray alloc] init];
//2
// this is all fine from here
self.parentTableView = parentTable;
//3
[self prepareTags];
}
return self;
}
I'm new in iPhone development and after reading Apple documentation and several posts here I still have some doubts about memory management. Please, supouse this basic class:
//MyClass.h
#interface MyClass : NSObject {
NSString *varA;
OtherClass *varB;
NSString *varC;
NSString *varD;
}
#property (nonatomic, copy) NSString *varA;
#property (nonatomic, retain) OtherClass *varB;
#property (nonatomic, copy) NSString *varC;
#property (nonatomic, copy) NSString *varD;
+ (id) initClass:(NSString *)desc;
- (void) method1:(NSString *)desc;
#end
With this implementation:
//MyClass.m
#implementation MyClass
#synthesize varA;
#synthesize varB;
#synthesize varC;
#synthesize varD;
+ (id) initClass:(NSString *)desc{
self = [super init];
if( self ){
self.varA = [NSString stringWithString:desc];
self.varB = [OtherClass initClassWithAutorelease:#"a description"]; //this class return an autoreleased object
[varB aMethod:#"something"];
}
return self;
}
- (void) dealloc{
[varB aMethod:#"something"];
[varA release];
[varB release];
[super dealloc];
}
- (void) method1:(NSString *)aString{
self.varC = aString;
self.varA = [NSString stringWithString:#"new value"];
[varB aMethod:#"something"];
}
#end
At this point what I have in mind is that the instance variables with #property have to be use without self. in the init method of the class and release them without self. in the dealloc, in other methods it is convinient to use self. for all cases. So here are my doubts:
First, I suppose that if I use self.varA= in the init method the retain counter increase so I have to release it in the dealloc method, even if the object has not been created with alloc, copy or new. Or I can use only varA= in the init and I will not need to do a release. For other class methods it's better to use the setter/getter so I can use self.varA=, ... appendString:self.varA ... or ...=self.varA without problem. Is all this correct?
Second doubt, what is best in terms of memory management and simplicity, to assign to an instance variable an object in the init method with or without autorelease? If I assign to it one without autorelease I will have to dealloc it but if I use autorelease the variable could be released before I want (like the autoreleased self.varB = [OtherClass... that will be used in the dealloc method whenever the MyClass is released).
Third, do I have to dealloc all my instance variables even if I don't use them in the init method but I could use them (read/write) in other methods of the same class? (Like varC in method1 or varD that is not used).
Fourth, do I need to take care of varA after assigning the new value in method1 if I did it well in the initClass and dealloc methods? In other words, will this generate memory leaks?
Fifth, if I declare with autorelease this class like an instance variable in a ViewController (MyClass *c; ... c = [[[MyClass alloc] initClass:#"description"] autorelease];) and I set the #property, do I have to do a release if I use it with c=... instead of self.c=...? As far as I know the behavior is the same than in my example so I should use the setter/get method in the viewDidLoad or viewWillAppear and released it in the dealloc without self..
Sixth and last one, for a instance variable is varA the same that self->varA?
Thanks...
At this point what I have in mind is that the instance variables with #property have to be use without self in the init method of the class and release them without self in the dealloc
This is completely the opposite of what is true. #property just makes the variable public outside of the class. If you have another class call that object, it will look in the header file (.h file), if it doesn't see a variable by that name, it will throw a warning during compile, and an error during runtime. When using properties with synthesize (btw, your synthesize can be all on one line, doesn't really matter though, ex: #synthesize varA, varB, varC;), using self automatically retains and keeps a retain count.
- (id) initClass:(NSString *)desc{ //Note the "-" instead of the "+" here, this is an instance method, not a class method
self = [super init];
if( self ){
[self setVarA:[NSString stringWithString:desc]];
[self setVarB:[OtherClass initClassWithAutorelease:#"a description"]];
[varB aMethod:#"something"];
}
return self;
}
in other methods it is convinient to use self for all cases.
Very untrue as well. If anything, this adds another call to the call stack and makes the execution slower (by one operation, but still, one more than needed). Consider this example:
[[self varA] doStuff:#"OMG"];
versus
[varA doStuff:#"OMG"];
The 2nd one will only access one pointer, where as the first one will have to access 2 pointers to get to the same result.
First, I suppose that if I use self.varA= in the init method the retain counter increase so I have to release it in the dealloc method, even if the object has not been created with alloc, copy or new.
Untrue. The class handles the first retain, and because of this, it handles a release as well. When your class is released, it sends a release to everything it has a retain on. If you do a release in your dealloc, this will actually decrease its retain count to -1 and create a memory error. If you set the property with self.varA = someObject, then it will give it a release when your class is dealloced. If you did self.varA = [someObject retain], then you would have to do a release in the dealloc.
Or I can use only varA= in the init and I will not need to do a release.
Kinda true, you would not need to do a release because you did not do a retain. But if something else lowers the retain count to 0 on this object, there is nothing in your class that forces the object to stay alive, and it will be freed, and if you reference it, memory error.
For other class methods it's better to use the setter/getter so I can use self.varA=, ... appendString:self.varA ... or ...=self.varA without problem. Is all this correct?
No, see why above. Only use [self setVarA:newValue] if you are changing the instance of the object, the synthesize will handle the rest. Otherwise just use [varA value] to get what ever data you need.
Second doubt, what is best in terms of memory management and simplicity, to assign to an instance variable an object in the init method with or without autorelease? If I assign to it one without autorelease I will have to dealloc it but if I use autorelease the variable could be released before I want (like the autoreleased self.varB = [OtherClass... that will be used in the dealloc method whenever the MyClass is released).
If you are creating a new object in init, autorelease it. You will have to release it in your dealloc if you do just a regular alloc init. The variable will not be released before you want it because of the retain you do on it through the property. EX
-(id) init {
self = [super init];
if(self) {
[self setVarA:[[[NSString alloc] init] autorelease]]; //Sets a new instance of NSString, autoreleased
}
return self;
}
This is correct, you do not need to do anything in your dealloc. You are creating an object with a retain count of 2 (one for the alloc you did here, and 1 for the retain you do when the synthesize sets the value in your class). Now, if it autoreleases, its retain will only go down by 1, and you will still have the retain from your property, so it will not release before your class releases
-(id) init {
self = [super init];
if(self) {
[self setVarA:[[NSString alloc] init]]; //Sets a new instance of NSString
}
return self;
}
Again, you create an object with a retain count of 2. You will need to do a [varA release] in the dealloc to knock the retain count down enough for it to be released when your class is released.
Third, do I have to dealloc all my instance variables even if I don't use them in the init method but I could use them (read/write) in other methods of the same class? (Like varC in method1 or varD that is not used).
No, you do not want to send releases to freed objects. You really should never use a dealloc in my opinion, but if you decide you want to for sure, then the worst case is to check to see if the object is null, and if its not, then release it
if(varD != null)
[[self varD] release];
Fourth, do I need to take care of varA after assigning the new value in method1 if I did it well in the initClass and dealloc methods? In other words, will this generate memory leaks?
No memory leaks from NSString. This method returns an autoreleased object. When you assign a new value to [self varA], it will release the old object, and retain the new object.
Fifth, if I declare with autorelease this class like an instance variable in a ViewController (MyClass *c; ... c = [[[MyClass alloc] initClass:#"description"] autorelease];) and I set the #property, do I have to do a release if I use it with c=... instead of self.c=...? As far as I know the behavior is the same than in my example so I should use the setter/get method in the viewDidLoad or viewWillAppear and released it in the dealloc without self..
You don't need a release in either scenario. The alloc increases the release count by 1, the autorelease will decrease it to 0. If you did self.c, that would increase it to 2, and decrease to 0 (one decrease from autorelease, and one from the property) when your class is released. You do not need to do ANYTHING in dealloc.
Sixth and last one, for a instance variable is varA the same that self->varA?
Yes, they point to the same location in memory.
when ever you write "alloc, retain, copy, new" you are responsible for releasing them in the dealloc method. ex
.h file
NSString * string;
#property (nonatomic, retain)NString * string;
.m file
#synthesize string;
-(void)dealloc{
[string release];
}
hope that helps :D
I have a property in my class, which is an NSArray. I am retaining the property.
My question is, what is the proper way to add objects to that array without leaking and making the retain count too high?
This is what I am using:
.h:
NSArray *foodLocations;
#property (nonatomic, retain) NSArray *foodLocations;
// I make sure to synthesize and release the property in my dealloc.
.m
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *tempFood = [[NSArray alloc] initWithArray:[self returnOtherArray]];
self.foodLocations = tempFood;
[tempFood release];
}
Is this the correct way to do it?
Yes this is correct and my preferred way of doing it as it renders the code more readable.
You are essentially allocating a temporary array and then assigning it to your property with a retain attribute, so it is safe to dealloc it as your property now "owns" it. Just remember that you still need to release it in your dealloc method.
You could also initialise the array and assign it to the property in the view controllers init method, depending on whether you need the property to be available to you before the view actually loads (i.e. in case you want to read the value of the property before pushing the view controller etc...)
you will typically want to declare the property copy in this case.
in most cases, immutable collection accessors should be copy, not retain. a lot of people get this wrong, and end up writing a lot of copying manually and sharing objects which should not be shared, thinking they are doing themselves good by cutting a corner.
copying in this form (the collection) is shallow. the objects in the array are not copied, just the array's allocation.
a good implementation of an immutable collection can simply implement copy by retaining self. if the argument is mutable, you want a copy anyhow (in the majority of cases).
your program is then simplified to a declaration of:
// note: copy, not retain. honor this if you implement the accessors.
#property (nonatomic, copy) NSArray * foodLocations;
and then the setter:
self.foodLocations = [self returnOtherArray];
of course, you must still init, dealloc, and handle thread-safety appropriately.
good luck
That looks fine. You don't actually need the tempFood variable, you can just do:
self.foodLocations = [[NSArray alloc] initWithArray:[self returnOtherArray]];
[self.foodLocations release];
or:
self.foodLocations = [[[NSArray alloc] initWithArray:[self returnOtherArray]] autorelease];
Or:
#synthesize foodLocations=_foodLocations;
then in code
_foodLocations = [[NSArray alloc] initWithArray:someOtherArray];
This avoids the autorelease required by
self.foodLocations = [[[NSArray alloc] initWithArray:someOtherArray] autorelease];
Yes, that is correct. Also good to keep in mind is what #synthesize is, in effect, doing for you. A synthesized (& retained) setter is functionally equivalent to the following code:
- (void)setVar:(id)_var {
[_var retain];
[var release];
var = _var;
[var retain];
[_var release];
}
So, basically, every time you call self.var = foo, it releases the previously stored value and retains the new one. You handle the reference counting in your code, and the setter handles its own.
I've read a few posts on this, but there's still one thing that's not clear for me. I know this might be rather a n00b question, but I've actually got rather far into development without quite grasping this fundamental issue. A symptom of being self taught I guess.
You declare a variable in your header, like so:
#interface SomeClass : NSObject {
NSMutableArray *anArray;
}
#property (nonatomic, retain) NSMutableArray *anArray;
end
And then in your main file you synthesise it and set it to an initial value:
#implementation SomeClass
#synthesize anArray
- (SomeClass *)init{
if (self = [super init]) {
self.anArray = [[NSMutableArray alloc] initWithCapacity:10];
}
[return self];
And release it when your Class deallocs:
- (void)dealloc {
[anArray release];
[super dealloc];
}
Now, when I run instruments, the line
self.anArray = [[NSMutableArray alloc] initWithCapacity:10];
is identified as a memory leak. Is it a memory leak because when you define the variable anArray in the header it allocates memory? (Because I thought it was a null pointer.) Therefore when you want to initialise it, and you call [[NSMutableArray alloc] initWithCapacity:10], you are reallocating the memory, and losing the pointer to the original allocation?
So instead, I use the convenience class method:
#implementation SomeClass
#synthesize anArray
- (SomeClass *)init{
if (self = [super init]) {
self.anArray = [NSMutableArray arrayWithCapacity:10];
}
[return self];
This is no longer identified as a memory leak in instruments. And since it's a convenience method, anArray is autoreleased. However, if I am to assume that the instance declaration in the header allocates memory, which would explain the previous issue, then should I still release anArray? Does setting the initial values in this way retain it perhaps?
I understand the difference between
NSMutableArray *anArray = [[NSMutableArray alloc] initWithCapacity:10];
and
NSMutableArray *anArray = [NSMutableArray arrayWithCapactiy:10];
but what I'm not sure I understand is when you've declared NSMutableArray *anArray in your header, which of the two approaches you should use and why. And whether or not if you use the second approach, you should still release anArray when you call dealloc.
I might add that I've found the following posts/links useful:
Suggest the best way of initialization of array ( or other objects )
What is the cost of using autorelease in Cocoa?
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
What is the difference between class and instance methods?
alloc'ing an object starts it off with a reference count of 1.
Setting a property that has the 'retain' attribute also increases the reference count.
So, that means this is usually bad:
#property (nonatomic, retain) Object * variable;
...
self.variable = [[Object alloc] init];
Because variable now has a reference count of 2.
When setting a object's member variable, just do this:
variable = [[Object alloc] init];
You should also realize that this works
self.anArray = [NSMutableArray arrayWithCapacity:10];
Because "arrayWithCapacity" (and other similar factor methods) autoreleases the object it returns, so after you set the property, it essentially has a reference count of 1.
It's not the instance that allocates the memory. You're right to assume that in Objective-C (at least on all Apple-based operating systems), newly initialized classes have all their ivars set to 0 (or nil or NULL as appropriate).
The problem you're seeing is that you're using the property, not the ivar in your initialization. Since you declared your property as retain, using the property accessor to set it automatically retains it.
So, when you initialize you either have to take ownership and set the ivar directly, or do like you're doing and use the property accessor to set the property and then relinquish ownership in the init method (by either releasing an object you own or, as you did in your second instance, using the convenience constructor so that you never owned the returned instance).
So just remember, if you ever use the property accessors, even within the class itself, you will get the features you set on the property (e.g., nonatomic, retain, etc.). You use the property accessors whenever you do one of the following:
// in these cases the property takes ownership through the
// retain keyword, so you must not take ownership yourself
self.anArray = something;
[self setAnArray:something];
[self setValue:something forKey:#"anArray"];
You would access your ivar directly like:
anArray = something; // in this case you must take ownership
Is this proper memory management? What I'm wondering is if I am supposed to release after the alloc in -viewDidLoad.
SomeViewController.h
#import <UIKit/UIKit.h>
#interface SomeViewController : UIViewController {
UIButton *someButton;
NSString *someString;
}
#property (nonatomic, retain) IBOutlet UIButton *someButton;
#property (nonatomic, copy) NSString *someString;
#end
SomeViewController.m
#import "SomeViewController.h"
#implementation SomeViewController
#synthesize someButton, someString;
- (void)viewDidLoad {
[super viewDidLoad];
someButton = [[UIButton alloc] init];
someString = [[NSString alloc] init];
}
- (void)viewDidUnload {
self.someButton = nil;
self.someString = nil;
}
- (void)dealloc {
[someButton release], self.someButton = nil;
[someString release], self.someString = nil;
[super dealloc];
}
#end
Thanks
Edit: one more thing. If I place a UIButton in IB, do I still need to alloc it?
It's quite a long story which you may find by googling around, and someone may enter here, but to keep it short, here's a few tweaks:
- (void)viewDidLoad {
[super viewDidLoad];
self.someButton = [[[UIButton alloc] init] autorelease];
self.someString = [[[NSString alloc] init] autorelease];
}
I.e. use the setters (self.something = ...;) and always either release or autorelease any alloc you do. (The logical distinction would be who "owns" the objects; with these tweaks the function gives up ownership and the class gets it.)
edit: no, if you create a button in IB, the button will just be there, allocated and initialized with your styles.
When you call init on an object, the retain count goes to 1. You have two different setter attributes: one is "retain" for your UIButton, and the other is "copy" for your NSString. When you call
self.someButton = someUIButtonObject;
someUIButtonObject gets a retain message and so its retain count goes up to 1. In the case of your original code, calling release in dealloc will release one reference to someUIButtonObject, but it will still have a retain count of 1 and will thus be leaked.
The other case with your NSString has a different problem but still leaks memory. Here your call to [[NSString alloc] init] results in a new string object, and then calling
self.someString = someNSStringObject;
results in the creation of a brand new object which copies the content of someNSStringObject. In this case, someNSStringObject and the setter's copied object each have a retain count of one. Here, you leak the string you alloc init-ed because you no longer have a reference to it and it goes out of scope with a retain count of one.
A quick side note: I don't know what your actual code looks like, but don't forget that NSStrings are immutable (so just calling [[NSString alloc] init] is pretty useless) and UIButton needs a frame (try [[UIButton alloc] initWithFrame:(CGRect)frame];).
Basically you need to match each call to retain, copy, or alloc with a call to release (or autorelease). It is appropriate so use
self.someButton = [[[UIButton alloc] init] autorelease];
Which will release the object, though at some unknown time in the future. Don't use autorelease if your memory is very tight and you need memory ASAP. In that case you would do:
UIButton* tempButton = [[UIButton alloc] init];
self.someButton = tempButton;
[tempButton release];
which guarantees that you don't have large objects waiting around in your autorelease pool.
Also, always use the getters/setters to access these properties (self.someButton as opposed to someButton). That way you don't accidentally assign someButton to a new pointer and leak the old one.
When you create a button in IB, the XIB holds a reference to the button (+1 retain count). If you create an IBOutlet so you can access the button programmatically, you get another retain on the object, so if you have an IBOutlet to someButton, someButton has a retain count of 2 as soon as the XIB is loaded. You do not need to alloc the object, that is done automatically when the XIB is loaded into memory. Also, you are only responsible for releasing one reference to the button (your IBOutlet reference). In general, it is a good practice to release your reference as soon as you know you no longer need it. For example, if you know you need a button and have to do initial customization and nothing else, then you would probably do something like this:
-(void)viewDidLoad {
// Do some customization of someButton
[someButton release];
}
Otherwise you would probably release someButton in viewDidUnload since you know at that point you won't need the reference to the button anymore.
If your button is set in IB, you do not need to allocate it in the code (IB does it for you).
Basically, each object you created using alloc or new, should have a release somewhere in your code. If it's an interface variable, you should release them in the dealloc function.