views:

47

answers:

3

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.

+2  A: 

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.

Bryan McLemore
+2  A: 

The casting is irrelevant here, what's important is how you obtain the reference to the object. There's a good SO question here: http://stackoverflow.com/questions/6578/understanding-reference-counting-with-cocoa-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.

Ben Gottlieb
A: 
  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.

Georg