开发者

How to release or nil a type-casted object?

I am a bit confused about the objects which are initialized by type-casting. Like

UITextField *txtFld = (UITextField *)[self.view viewWithTag:someTag];
//
//
//some code here for this text field usage
//
//

now when I am finished using this text field should I set it to nil or leave it as it is for the system to take care of it.

Now in the case of the objects of a database class(using sqlite) I create开发者_如何转开发 an object like

DatabaseClass *dbObj = (DatabaseClass *)[[appDelegateObject dbObjArray] objectAtIndex:index];

Should I set it to nil too after I am finished with this object

or should initialize the object like:

DatabaseClass *dbObj = (DatabaseClass *)[[[appDelegateObject dbObjArray] objectAtIndex:index] retain];

and then release it and finally set it to nil.


When you type cast like that there is not a new object being created. It just tells the compiler that the object you're using should be treated as if it were, in this case, a DatabaseClass *.

So in this case I believe viewWithTag: is going to returned a object that you won't need to do anything retain/release with unless you're wanting to keep it around as an ivar.

I hope that helps.


The casting is irrelevant here, what's important is how you obtain the reference to the object. There's a good SO question here: Understanding reference counting with Cocoa and Objective-C that covers retain/release issues. Basically, you don't have to do anything in these cases, since you're getting objects back that are not owned by you.


  1. You don't have to cast the type. Objective-C is a dynamic language. Please correct me if this throws a compiler warning

     DatabaseClass = *dbObj = [[appDelegateObject dbObjArray] objectAtIndex:i];
    
  2. All methods should return autoreleased objects in Cocoa. Exceptions: all copy methods and all alloc methods.

    Therefore it's save to not retain/release them because they are autoreleased.

  3. Settings variables to nil has only an effect in a garbage collected environment. As long as you're programming for the iPhone this doesn't matter to you.

    But even in a garbage collected environment settings a variable to nil isn't necessary because the compiler should be able to automatically find out which variables aren't needed anymore.

    There is an exception to this. You can and sometimes should set an instance's property to nil in a GC environment.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜