iPhone - dealloc - Release vs. nil - iphone

Wondering if someone with experience could possibly explain this a bit more. I have seen examples of...
[view release];
view = nil;
....inside the (void) dealloc.
What is the difference and is one better then the other?
What is the best way?
When doing retainCount testing I have personally seen nil drop a count from 3 to 0 for me, but release only drops it from 3 to 2.

What you have seen is probably these:
1) [foo release];
2) self.bar = nil;
3) baz = nil;
Is releasing the object, accessing it through the instance variable foo. The instance variable will become a dangling pointer. This is the preferred method in dealloc.
Is assigning nil to a property bar on self, that will in practice release whatever the property is currently retaining. Do this if you have a custom setter for the property, that is supposed to cleanup more than just the instance variable backing the property.
Will overwrite the pointer baz referencing the object with nil, but not release the object. The result is a memory leak. Never do this.

If you are not using properties (where self.property = nil will also release an object) then you should ALWAYS follow a release by code that sets the reference to nil, as you outlined:
[view release]; view = nil;
The reason is that it avoids he possibility that a reference can be used that is invalid. It's rare and hard to have happen, but it can occur.
This is even more important in viewDidUnload, if you are freeing IBOutlets - that's a more realistic scenario where a reference might go bad because of memory warnings unloading a view, and then some other code in the view trying to make use of a reference before the view is reloaded.
Basically it's just good practice and it will save you a crash at some point if you make it a habit to do this.

#bbullis22 you have seen the restain count drop from 3 to 0 because you set the reference to nil. then you asked for the retaincount of 'nil' which is zero. however, the object that used to be referenced has the same retain count - 1 (due to setting the reference to nil).
using release, the reference still references the same object, so that's why you see the retain count drop from 3 to 2 in this situation.

As far as usage inside your code, in your dealloc you don't need the assignment to the property, releasing is all you need to do.
- (void)dealloc {
[myProperty release]; // don't need to assign since you won't have the object soon anyway
[super dealloc];
}

I think using both is kind of safety net. With only release in place you could run in problem if you screwed reference counting management. You would release an object, giving its memory back to system but pointer would be still valid.
With nil you are guaranteed that program will not crash since sending message to nil does nothing.

Related

Object c property dealloc, which one is correct? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dealloc method in iOS and setting objects to nil
As to property dealloc in object c, i have seen different kinds of forms. Which of following is best/correct
//Kind1:
- (void)dealloc
{
[_property release];
[super dealloc];
}
//Kind2:
- (void)dealloc
{
self.property = nil;
[super dealloc];
}
//Kind3:
- (void)dealloc
{
[_property release]; _property = nil;
[super dealloc];
}
Your second option is inadvisable. Property setters may have side-effects and generally aren't implemented with the consideration that the object may be half torn down already. In general you should avoid any method calls to self (or super) from dealloc, other than [super dealloc]. You should also avoid non-trivial calls (i.e. anything but release) on other objects, as you may have circular references that can lead back to references to your half-deallocated object.
The first option is perfectly sufficient. Note that if you use ARC it is redundant. Using ARC is your best bet, invariably, as it's not only safer but faster.
The third option is controversial. Some people argue that it makes your program more resilient to errors (since references after dealloc may end at the zeroed instance variable, rather than bouncing through it and seg faulting, or worse). They also argue that it ensures that if you do run a method which tries to use the value, it'll probably fail gracefully (again, rather than dereferencing what is a dangling pointer at that point). But if you subscribe to my first point on avoiding this to begin with, it becomes somewhat moot. And my experience is that relying on that behaviour is a bad idea - even if it's a clean design to begin with, it's easy to forget about it and end up changing the code some time later, in a way that breaks it.
And those that dislike the third option also argue that it hides errors. Some go as far as explicitly overwriting not with nil but rather an obviously bogus value (e.g. 0x0badf00d) to make it clearer if and when a dangling pointer is dereferenced.
Kind1 is more than enough;
It is usually not a good idea to use 'self' on alloc and dealloc. coz self will call setter/getter method, and if u have custom setter/getter method its can cause trouble.
You should never call self. in dealloc.
Once you have release-ed then there is no advantage whatsoever of making it nil.
So, first one is the correct way to use dealloc.

Objective-C pointers/memory management question

I am testing the following code below. ffv is declared in the interface file.
ffv = [[FullFunctionView alloc] initWithFrame:self.view.bounds];
NSLog(#"%i", [ffv retainCount]); // prints 1
[self.view insertSubview:ffv belowSubview:switchViewsBtn];
NSLog(#"%i", [ffv retainCount]); // prints 2
[ffv release]; // you can release it now since the view has ownership of ffv
NSLog(#"%i", [ffv retainCount]); // prints 1
if (ffv == nil)
NSLog(#"ffv is nil");
// "ffv is nil" is not printed
[ffv testMethod]; // "test method called" is printed
this is my [ffv testMethod] implementation
- (void)testMethod
{
NSLog(#"test method called");
}
What I deduce in this case is that even if you release an object with retain count 2, you lose ownership of that object however, the reference is still kept.
Now, my question are:
Is my deduction correct?
Is there anything else important that can be deduced from this?
What are the complications caused by still keeping (using) ffv and calling methods from ffv? (My opinion is that this is ok since the view will always own ffv and won't release it until someone calls viewDidUnload. And as long as I don't pass ffv's reference to other objects.)
There are a couple of problems with using ffv after you have released it and it's only retained by your view controller's view.
1) It introduces a potential for future bugs, because later you might not remember that ffv is otherwise not retained. When you release the view (e.g. by replacing it with another view), you have a dangling pointer that you still hold a reference to.
2) In the special case of a UIViewController the view could be released at any time (you usually never call viewDidUnload yourself). The default behavior of UIViewController, when receiving a memory warning and the view is currently not visible, is to release the view, so unless you set the reference to nil in viewDidUnload, you have a dangling pointer again, even though you never explicitly released the view yourself.
1) Is my deduction correct?
Your deduction is correct. The Memory Management Programming Guide explains that each object has one or many owners. You own any object you create using any method starting with alloc, new, copy, or mutableCopy. You can also take ownership of an object using retain. When you're done with an object, you must relinquish ownership using release or autorelease.
Releasing the object doesn't change the value of any variables that reference that object. Your variable contains the object's memory address until you reassign it, no matter what retain count the object has. Even if the object's retain count goes to zero, causing the object to get deallocated, your variable will still point at that same address. If you try to access the object after it's been deallocated, your app will normally crash with EXC_BAD_ACCESS. This is a common memory management bug.
2) Is there anything else important that can be deduced from this?
Nothing comes to mind.
3) What are the complications caused by still keeping (using) ffv and calling methods from ffv? (My opinion is that this is ok since the view will always own ffv and won't release it until someone calls viewDidUnload. And as long as I don't pass ffv's reference to other objects.)
When you call release, you are telling the Objective C runtime that you no longer require access to the object. While there may be many cases like this one in which you know the object will still exist, in practice you really shouldn't access an object after calling release. You'd just be tempting fate and setting yourself up for future bugs.
I personally don't like peppering my code with release statements, because I don't trust myself to remember them 100% of the time. Instead, I prefer to autorelease my variables as soon as I allocate them like this:
ffv = [[[FullFunctionView alloc] initWithFrame:self.view.bounds] autorelease];
This guarantees that ffv will exist at least until the end of the method. It will get released shortly thereafter, typically before the next iteration of the run loop. (In theory this could consume excessive memory if you're allocating a large number of temporary objects in a tight loop, but in practice I've never encountered this case. If I ever do, it will be easy to optimize.)
The object is not deallocated until the retain count goes to 0. As long as it's not deallocated, you can keep using it without trouble. By retaining it you ensure that it won't be deallocated under your feet; however, if you retain another object that you know retains the first object, you can get away with this form of "indirect retaining". Don't complain when you move things around later and things start breaking, though.
if (ffv == nil)
NSLog(#"ffv is nil");
// "ffv is nil" is not printed
That's correct, releasing an object does not set the pointer to nil even if it is dealloced at that time. Good practice is to always set your pointer to nil after you release it.
You are correct to say that after you released it, it wasn't dealloced because the view still had a retain on it. But that's not how you should be thinking about it. If you want to use that object and you want it to be alive, retain it. Doesn't matter who else is retaining it. Your object has nothing to do with those other objects. You want it, retain it. You're done with it, release it and set your pointers to nil. If you don't set it to nil and everyone else also released it, you will have a dangling pointer to an object that was dealloced, and that will cause you a crash and much grievance.
so this:
[ffv release]; // you can release it now since the view has ownership of ffv
ffv = nil; // you released it, so that means you don't want it anymore, so set the pointer to nil
if you still want to use it, don't release it until you're done with it.
Well, I'm not sure 'losing' ownership is the right term. In Objective-C you have to carefully marshal your ownership of the object. If you create or retain an object, you are responsible for releasing it (either directly or via an autorelease pool). When you call release however, you don't lose a reference to the object, if something else has retained it, it will still be in memory, and your pointer will still potentially point to it.
You have a pointer ffv which is just a pointer to some memory, and you have the object which is created in the first line that ffv points to.
By calling release, you are stating that you no longer require the ponter ffv to point to a valid object, that in this context you would be happy for the object to be deallocated. The pointer still points to that bit of memory, and it is still there because its retain count was increased by assigning it to the view.
The line [ffv testMethod] is in danger of not working, as it follows the release and may not point to a valid object. It only works because something else is keeping it alive. ffv still has the same address value that it had when it was first assigned.
So in order:
Your deduction is correct.
Not really.
You shouldn't use ffv after the release call. You have no guarantee that the object is going to be there for you.
These are pointers we are using here, not references like you find in Java or C#. You have to marshal your ownership of the object, you create it, have some pointers to it and by careful management of retain and release calls you keep it in memory for as long as you need it.

problem with nil and release?

i am using NSArray named as allAvailableServices .
first i initialize it and after wrote [allAvailableServices release];
then i checked the condition if(allAvailableServices).
it came as true!may i know the reason.
then i wrote
allAvailableServices = nil; and [allAvailableServices release];
after the above code if(allAvailableServices) came false.is there any problem that i wrote [allAvailableServices release]; after allAvailableServices = nil;
whenever allAvailableServices = nil i need to allocate new array.so if i didn't call [allAvailableServices release]; i think there is a memory problem.am i correct?
can any one provide me a best way to deal with it?
Release just reclaims the memory, but the pointer value isn't changed; it still contains a value, but it points to garbage.
This is why many people nil their pointer after releasing it:
[allAvailableServices release], allAvailableServices = nil;
In Objective-C, it is safe to send a message to nil, but sending a message to an object that has been released may cause the app to crash (usually with EXC_BAD_ACCESS)
Note, that I've released the object before setting it to nil. If you do it the other way around, you've lost the pointer to which you send the release message, and so you've leaked the object.
If you use accessors then you can directly set the values to nil, it calls the release and sets them to nil. A release decrements the reference count by 1 and if it reaches 0 the object is freed.
The memory still has some value if you do not set to nil and hence the problem in your if condition.
Cleaner way is to use accessors and call self.yourvariable = nil; .

What's the difference between setting an object to nil vs. sending it a release message in dealloc

I have Object:
MyClass *obj= [[MyClass alloc] init];
What's the difference between:
[obj release]; // Only obj own this object.
and:
obj = nil;
Does iOS deallocs obj when i set obj = nil?
I have a pointer, sometime i set it point to an object, sometime do not. So, when i want release a pointer i must check is it nil?
This answer from the previous decade,
is now only of historic interest.
Today, you must use ARC.
Cheers
The very short answer is DO NOT just set it to nil. You must release it. Setting it to nil has no connection to releasing it. You must release it.
However it's worth remembering that if it is a property, then
self.obj = nil;
will in a fact release it for you. Of course, you must not forget the "self." part !!!!
Indeed,
self.obj = anyNewValue;
will indeed release the old memory for you, clean everything up magically and set it up with the new value. So, self.obj = nil is just a special case of that, it releases and cleanses everything and then just leaves it at nil.
So if anyone reading this is new and completely confused by memory,
You must release it, [x release] before setting it to nil x=nil
IF you are using a property, "don't forget the self. thingy"
IF you are using a property, you can just say self.x=nil or indeed self.x=somethingNew and it will take care of releasing and all that other complicated annoying stuff.
Eventually you will have to learn all the complicated stuff about release, autorelease, blah blah blah. But life is short, forget about it for now :-/
Hope it helps someone.
Again note, this post is now totally wrong. Use ARC.
Historic interest only.
Is It Necessary to Set Pointers to nil in Objective-C After release?
Release, Dealloc, and the Self reference
Setting an object nil versus release+realloc
Read the above. They answer your Q comprehensively
iOS does not support garbage collection, which means that doing obj = nil would result in a memory leak.
If you want automatic control over deallocation, you should do something like: obj = [[[NSObject alloc] init] autorelease] (you must NOT release it if you do that).
Autorelease would cause the object to be automatically released when the current NSRunloop event ends.
The NSRunloop automatically drains it's NSAutoReleasePool for each event iteration, which is usually very helpful.
Setting an object nil will create a memory leak(if you are taking ownership by alloc,retain or copy) because we are not having a pointer to that particular memory location.
so if you want to dealloc an object you have to take out all ownership of an object before making it nil by calling release method.
[obj release];
obj=nil;

Objective-C (iPhone) ivars and memory management

I am subclassing NSURLConnection, and used MGTwitterEngine as a base to help me get started. That may be irrelevant. However, I noticed in their code they don't use #property or #synthesize for their ivars. They have wrapped the ivars in accessor methods which look like this:
- (NSString *)identifier {
return [[_identifier retain] autorelease];
}
My question is two part. First, what effect does retain followed by autorelease have? It seems to me it would cancel itself, or worse yet leak.
Second, if I were to change the header file to have:
#property (nonatomic, retain, readonly) NSString* _identifier;
And used #synthesize indentifier = _identifier, wouldn't this do the same thing as the accessor method without having to write it?
Maybe it is just two different ways to do the same thing. But I wanted to ensure I have the correct understanding. Thanks.
Using #synthesize will actually only create a setter and a getter method. The code that is auto generated for you is guaranteed to use proper memory management, so that you do not need to worry.
MGTwitterEngines use of return [[ivar retain] autorelease] is actually the correct way to do it. Lets have two examples.
Assume a getter is defined as this:
-(Foo)foo {
return foo;
}
And then we execute this code:
bar = [[bar alloc] init]; // bar has aretain count of 1.
foo = bar.foo; // foo har a retain count of 1 (owned by bar).
[bar release]; // Bar and all it's ivars are released imidiatetly!
[foo doSomething]; // This will crash since the previous line released foo.
If we instead change the getter to this:
-(Foo)foo {
return [[foo retain] autorelease];
}
bar = [[bar alloc] init]; // bar has a retain count of 1
foo = bar.foo; // foo has a retain count of 2 (one owned by bar, 1 owned by autorelease pool).
[bar release]; // Bar and all it's ivars are released imidiatetly!
[foo doSomething]; // Will not crash since foo is still alive and owned by autorelease pool.
Hope this explains why you should always return properly autoreleased objects from all your getters. It is important that any return value can survive the deallocation of it's parent, since no class ca guarantee what a client will do with it's values once it is exposed to the wild.
Retain followed by autorelease does exactly what you might think it does. It sends the object a retain message and then sends it an autorelease message. Remember that autoreleasing an object adds that object to the autorelease pool but does not release it yet. The autorelease pool will send the object a release message at the end of the current iteration of the run loop. So, a retain followed by autorelease essentially says, "Make sure this object stays around until the end of the the current iteration of the run loop." If you need the returned value to hang around longer, you can retain it. If not, do nothing and the autorelease pool will handle it.
In this case, the string being sent retain and autorelease messages is a property. It's already retained by the parent object. So you might wonder why do this retain and autorelease thing at all? Well, there's no guarantee that the object won't release _identifier before the current iteration of the run loop ends. Consider this example:
- (NSString *)identifier { return _identifier; }
- (void)aMethod {
NSString *localId = [self identifier]; // localId refers to _identifier which is only retained by self
[self methodThatChangesIdentifierAndReleasesItsOldValue]; // self releases _identifier
NSLog(#"%#", localId); // crash, because localId (old value of _identifier) has been released
}
In this case, the returned identifier isn't retained and autoreleased. The NSLog line crashes because localId refers to a released string. However, had we used retain and autorelease in the getter, there would be no crash because localId would not be released until the end of the current iteration of the run loop.
As far as I know, your replacement with an identifier property would be just as good. It might not be identical code, but the effect should be the same.
Apple explains this well in Implementing Accessor Methods. The method quoted by you (named "Technique 1" by Apple) helps avoid bugs if the caller assigns a new value to the identifier property and then expects the retrieved value to still be available. It won't be needed most of the time but just returning the ivar value can lead to bugs that are hard to track down.
Generally one retains then autoreleases if you are returning something that you didn't own the first place. It will only leak if you own _identifier and there is a mismatch of retain/alloc/etc versus release/autorelease sent to that object.
Secondly, yeah you generally don't have to write the headers if you aren't doing something special beyond what the general boilerplate looks like. Apple has good documentation on properties, I suggest if you're still fuzzy, you look at those.