Since the variable b
is completely internal to class A
, and is not declared as @public
(the default is @protected
), the best way to know if b
has been deallocated is to release it and set the pointer to nil
. That way, you can just check if (b == nil)
and create a new instance if necessary.
The bigger question, however, is what the true nature and memory behavior of b
is. You state that "object B can be freed in memory low levels", but don't explain why. If you're using the standard idioms for retain-release in Objective-C, I would think that A would be the one to determine whether B should be deallocated, since it's creating a new instance. If you don't intend for A to make such decisions, allowing it to allocate a new B will lead to ownership confusion and memory bugs down the road.
If A is not in charge of B, and if you are on Leopard (or beyond) and have garbage collection enabled, what you may want is a zeroing weak reference. This is declared using __weak
before an instance variable declaration, and doesn't prevent the garbage collector from collecting the object it points to. (A "strong" reference is the default, and the garbage collector won't deallocate object it can trace from a root through only strong references.) Further, the GC will automatically set weak references to 0 for you if/when the object is deallocated.
Coming back to "the bigger question", unless b
is already a weak reference and GC is on, (and a few other conditions hold), the system will not automatically deallocate B for you. If the reason for deallocating b
is that instances of B grow over time, (such as a cache of dispensable items), it would be much better to have a way to empty B. For example, mutable collections in Foundation have a -removeAllObjects
method. Such an approach would avoid most of the confusion about whether b
still exists, and is much more efficient than repeatedly (de)allocating objects.