开发者

ivar check if it has been initialized and used

let's say I have an instance variable MyObject* test;

@property(nonatomic, retain) MyObject* test;

.m

@synthesize test;

I might initialize it or might now depending if I need to. If I don't need it, no point wasting on initialization.

The question is in the dealloc, is i开发者_开发技巧t safe to do the following check and release?

-(void) dealloc
{
  if ( test != nil )
  {
   [test release];
  }
{

Thanks!


Yes, it is safe. However, sending release to a nil won't cause any trouble, so you don't need to check for that.


that's perfectly fine. it is also more idiomatic to simply omit the test for nil.

behind the scenes, the compiler (typically*) generates a call to objc_msgSend or one of its variants. the implementation of objc_msgSend (and variants) allows the object you message to be nil, in the sense that it is well defined and not considered a programmer error to message nil. the return value of objc_msgSend+ variants is zeroed:

example:

NSString * string = nil;
NSString * copy = [string copy]; << copy will be 0/nil
NSUInteger length = [copy length]; << length will be 0

this means you must test for nil if returning a c++ object -- the constructor will not be invoked if the receiver is nil.

*typically, in the sense that there is a handful of c functions the compiler calls to perform messaging as well as some other common routines.


You don't need to do that. You can simply do this if you assign an autoreleased object to the ivar:

self.test = nil;

Edit:

Don't forget to call [super dealloc] at the end of the dealloc function


It's safe but not standard practice. You can safely send messages to nil references, and this is a big part of how idiomatic Objective-C is written. Simply release the ivar:

- (void)dealloc
{
    [test release];
    // ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜