What explains best the difference between [myVar dealloc] and [myVar release]? - iphone

I think I know the difference, but don't know how to explain that correctly.
dealloc removes the memory reserved by that variable totally and immediately.
release decrements the retain counter of that variable's memory by -1. if it was 1, then it's 0, so it would have the same effect as dealloc in that moment.
is that right? or is there an better short explanation?

That's exactly right.
But you wouldn't use dealloc, when using an object, because you don't know what the retain count is. Nor do you care. You just say that you don't need it anymore, by calling release. And once nobody does, the object will call dealloc on itself.

All correct, but the one key point you're missing is that you should never call dealloc yourself. Here's some information from Apple's documentation on NSObject's dealloc method:
(from http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/dealloc)
You never send a dealloc message
directly. Instead, an object’s dealloc
method is invoked indirectly through
the release NSObject protocol method
(if the release message results in the
receiver's retain count becoming 0).
See Memory Management Programming
Guide for Cocoa for more details on
the use of these methods.
Subclasses must implement their own
versions of dealloc to allow the
release of any additional memory
consumed by the object—such as
dynamically allocated storage for data
or object instance variables owned by
the deallocated object. After
performing the class-specific
deallocation, the subclass method
should incorporate superclass versions
of dealloc through a message to super:

Related

Does ARC insert code in -dealloc before or after any custom -dealloc code?

With ARC sometimes I still need to write a -dealloc method to do some cleanup. In some rare cases I need to refer to properties of the instance to properly do cleanup. Such as unregistering from NSNotificationCenter with a given sender object, which is owned and referenced by a property.
Does ARC insert it's property release code at the end of after my own code, or does it insert this at the beginning of -dealloc, before my own code?
If ARC would be inserting code before any custom -dealloc code, then this would be very dangerous since you can't access properties anymore if needed.
This question is about where ARC inserts the property release code in a synthesized -dealloc, and not about wether or not to implement -dealloc.
I think, that everything is said here: http://clang.llvm.org/docs/AutomaticReferenceCounting.html#misc.special_methods.dealloc
7.1.2. dealloc
A program is ill-formed if it contains a message send or #selector expression for the selector dealloc.
Rationale: there are no legitimate reasons to call dealloc directly.
A class may provide a method definition for an instance method named dealloc. This method will be called after the final release of the object but before it is deallocated or any of its instance variables are destroyed. The superclass's implementation of dealloc will be called automatically when the method returns.
Rationale: even though ARC destroys instance variables automatically, there are still legitimate reasons to write a dealloc method, such as freeing non-retainable resources. Failing to call [super dealloc] in such a method is nearly always a bug. Sometimes, the object is simply trying to prevent itself from being destroyed, but dealloc is really far too late for the object to be raising such objections. Somewhat more legitimately, an object may have been pool-allocated and should not be deallocated with free; for now, this can only be supported with a dealloc implementation outside of ARC. Such an implementation must be very careful to do all the other work that NSObject's dealloc would, which is outside the scope of this document to describe.
ARC releases instance variables at the end of the dealloc chain. In other words, all the dealloc methods in the inheritance chain are run, and then any ARC-managed instance variables will be deallocated. You could think of it as happening in -[NSObject dealloc], though it's really even later than that.
So rest assured; ARC won't release your properties out from under you in your -dealloc method. ARC won't release them until you have no way to reference them anymore.

iPhone - Is there a way to know if a reference is (still) valid?

Let's say I assign an instance var with an object given in parameter. I don't know what this object is, so I don't want to retain it. But, that reference I have to that object can be invalid at some time, for example if the object is released, or is about to be released (autorelease pool). So, inside my class instance, can I know if the reference I have kept into an instance variable can be used without any risk of crash?
You should retain it and release it when you no longer need it. That is exactly what retain is for.
Kris Van Bael is right, no matter if you know what the object is, if you want to have ownership of it (if it's up to you to ensure that the object is alive), you must retain it. Release it when you don't need it, and set the reference to NIL (for security).
But their is an exception !
Sometimes you don't want to have ownership, the most common example is the delegate.
You don't want to retain your delegate, because it probably already retains you, and if both objects release each other in the dealloc method, your app will leak.
But in this case, you shouldn't care about the delegate being deallocated : the delegate should set your "delegate" property to nil in it's dealloc method.
So
if you have ownership on the object : retain, no choice !
if the object has ownership on you : assign, and don't worry !
This approach is really dangerous. If your app is not able to track object life cycle, then you must change the code in order to have control of this.
Anyway answering to your question: you can protect your instance variable by extra retaining it in your class and then releasing it when it is no more needed. So you don't need to do the check you are asking for.
You should set any released reference to NIL and check for NIL.

Any way to check if an instance is still in memory?

Example: I have a view controller and get rid of it. But there's still an variable holding it's memory address. Accessing that results in EXEC_BAD_ACCESS. Of course. But: Is there any way to check if that variable is still valid? i.e. if it's still pointing to something that exists in memory?
You need to read this again:
Cocoa Memory Management Guidelines
In short, if you want something to stick around you must retain it.
If you want something to go away and you have previously retained it, you must release or autorelease it.
You must never call dealloc directly (except [super dealloc]; at the end of every one of your dealloc methods).
You must never release or autorelease an object that you did not retain.
Note that some methods do return retained objects that you must release. If you alloc an instance of a class, that implies a retain. If you copy and instance, the copy is retained.
If you are ever tempted to use the retainCount method, don't. It isn't useful. Only consider retain counts as a delta; if you add, you must subtract, but the absolute value is an implementation detail that should be ignored.
(In other words, even if there were ways to check for an object's validity definitively -- there aren't -- it would be the wrong answer.)
Oh, and use the Build and Analyze feature in Xcode. It does a very good -- but not quite perfect -- job of identifying memory management problems, amongst other things.
That's what the entire memory management model is set up for - if you call retain at the right times, and release and autorelease at the right times, that can't happen. You can use NSZombie to help you debug.
Use "NSZombieEnabled" break point.
For this reason only all strongly recommend us to use accessors. If your object is released anywhere, it will get assigned to nil, and there will be no harm if you call any API or method on Nil object. So please make a habit of using Accessors.
you just add this NSZombieEnabled Flag as an argument to your application in build settings. and enable it. Now you run your application in debug mode. If any such crash is about to occur, this breakpoint will show you which object is freed and where it is crashing.
Cheers,
Manjunath
If by variable, you mean whether the pointer to your object still references valid memory then:
MyClass *myVariable = [[MyClass alloc] init];
//Tons of stuff happens...
if (myVariable != nil)
//Do more stuff

Do I need to explicitly alloc my NSNumber?

I am defining a number, as follows:
NSNumber *nn0 = [NSNumber numberWithInt:0];
It works fine without any alloc. My understanding is that if I use numberWithInt, alloc and init are called automatically.
If I try to release at the end of my function, I run into problems:
[nn0 release];
I get a runtime error.
My question is: if I use numberWithInt to initialise the NSNumber, do I have to do any memory management on it?
The "convenience constructors" for a lot of types produce an object that is automatically "autoreleased" - i.e. the new object will be retained by the current NSAutoreleasePool. You don't need to manually release these objects - they will be released when the current NSAutoreleasePool is released/drained.
See this page for a description of convenience constructors, and how to mange the memory for these.
http://www.macdevcenter.com/pub/a/mac/2001/07/27/cocoa.html?page=3
Just follow the core memory-management rule: If you "own" the variable, you have to eventually relinquish ownership. You take ownership by: creating the object (alloc/new/copy) or specifically taking ownership (retain). In all these cases, you're required to release it.
If you need the object to stick around, you need to take ownership of it. So if you know you only need the number for this method (like to pass it into an array or whatever), use the convenience method and just leave it at that. If you want to keep the number for some reason (and instance variable, for example), then you can safely alloc/init it.
If you release something that you don't own, you will get a runtime error.
The rule is simple, with very few exceptions:
If the selector returning an object has the word "new", "alloc", "retain" or "copy" in it, then you own the returned object and are responsible for releasing it when you are finished.
Otherwise you do not own it and should not release it. If you want to keep a reference to a non-owned object, you should call -[NSObject retain] on that instance. You now "own" that instance an must therefore call -[NSObject release] on the instance when you are done with it. Thus you do not own the instance returned by -[NSNumber numberWithInt:] and should not call -release on it when you are done. If you want to keep the returned instance beyond the current scope (really beyond the lifetime of the current NSAutoreleasePool instance), you should -retain it.
In RegEx terms, Peter Hosey lays it out very nicely in his blog. You own the returned object instance if the method selector matches this regex:
/^retain$|^(alloc|new)|[cC]opy/
Of course, the definitive reference is the Memory Management Programming Guide for Cocoa.

iphone memory management issue

How to check if an object has been released from the memory?
I know a object has to be released manually when we use alloc|copy|retain to create that object. if use the instance class method (NSString stringwithformat:), the object will be released automatically by NSAutoRealeasePool, however, sometime there have some object used to release at the (void)dealloc function there.
Can anybody tell me
What is the difference between [object release] instantly after alloc function, [object release] at (void)dealloc,and NSAutoReleasePool to release the object?
When is the (void)dealloc function being called and when is the NSAutoReleasePool release the memory, I know it is every loop cycle, how can I check it from code?
When I declared a variable in the header and set the property as retain, I still can use the alloc function to that object but not cause a memory leak, but from this post it seems like once declared a retain object at header, then you no longer can alloc the object because both will retain the object,can anybody tell me why I still can code like this without causing any memory leak?
[object release] releases your object immediately. After sending a release message you should not use the object again - unless you absolutely know you still have a retain on that object. If yours was the last retain the memory could be freed during the call to release.
Autorelease frees an object 'sometime later' the system does not guarantee anything about the meaning of 'later' other than that it will be after the scope of the current message.
See above, there is no real qay to guarantee when dealloc is called following autorelease from the point of view of your code. You should just assume it is sometime after the return of the method where you send the autorelease message.
You simply need to balance retain and release. If you have one to many (as is likely i nthe situation you describe) that is a leak. Conversely if you have unbalance the other way, you will generate a more destructive error when you access freed memory.
The correct sequence for a retained property is:
alloc init // retain == 1
set the property // retain == 2 due to setProperty calling retain.
release the object // retain == 1
Which leaves a retain count of one, no memory leak.