views:

267

answers:

4

If I create a new object that includes two object pointers (see below) when the object is created the pointers are set to point to nil;

@interface rocketShip : NSObject {
    NSString *name; 
    NSNumber *thrust;
}

If (for some unexpected reason) I don't assign these pointers and later release them in my dealloc method is that ok, I am pretty sure it is, just wanted to check?

- (void)dealloc{
    [name release];
    name = nil;
    [thrust release];
    thrust = nil;
    [super dealloc];
}

gary

+10  A: 

Sending a message to nil won't cause an error, so this is fine. You need to make sure the pointers are actually nil though - sending a message to a garbage pointer will likely cause errors.

Adam Wright
+6  A: 

Yes, you can do this because you can safely send a message (such as release) to nil and it will just do nothing.

gavinb
A: 

If you use the accessor property to create your get/set methods:

@interface rocketShip : NSObject {
    NSString *name; 
    NSNumber *thrust;
}

@property (retain, nonatomic) NSString *name;
@property (retain, nonatomic) NSNumber *thrust;

And in your .m file:

@synthesize name;
@synthesize thrust;

You can then just set your variable to nil in dealloc. This will in fact call your setter and decrement the reference count by one and clean things up.

Vincent
fuzzygoat
As a clarification, you would have to write self.name = nil in dealloc. Simply setting name = nil would be a leak except under GC.
sbooth
Although it will work in the simplest case, Vincent's suggestion is not best practice. Using `self.name = nil` in the dealloc method will call your setter method. If a subclass (or you) overrides this setter method such that it has side effects or depends on instance state, it may break when called from dealloc where instance state is not determined. It is *much* better to call [name release].
Barry Wark
A: 

It’s important in Objective-C to distinguish between objects and variables. You cannot release a pointer (the value of a variable), you can only release an object (the object to which a pointer refers). A nil pointer refers to no object, so messages sent to nil do nothing (which is generally safe).

Ahruman