views:

39

answers:

3

Is there a reason, other than as may be required by object scope across different methods of the object, to use an object like this:

@interface
...
ViewMgmtAppDelegate : NSObject <UIApplicationDelegate> {
Obj *obj1;
...
}
@end

@implementation
- (void)applicationDidFinishLaunching:(UIApplication *)application {
obj1 = [Obj alloc];
[window addSubview:obj1]; 
...
}
- (void)dealloc {
[obj1 release];
...
}
@end

Instead of this:

@interface
...
ViewMgmtAppDelegate : NSObject <UIApplicationDelegate> {
...
}
@end

@implementation
- (void)applicationDidFinishLaunching:(UIApplication *)application {
Obj obj1 = [Obj alloc];
[window addSubview:obj1]; 
[obj1 release];
...
}
- (void)dealloc {
...
}
@end

Is either way more efficient?

Any help appreciated // :)

+1  A: 

You would use your first example in case that your obj1 will be used after the view finished loading. For example after a click event.

The second example will be used if this is not the case. So Obj1 is not needed anymore after the release and does not need to use the RAM of the iPhone.

Ghommey
+1  A: 

I assume you are asking if you should release the object right after addSubview or in dealloc.

It depends on the application logic and what addSubview does. If addSubview retains the object you can release it right after the call if you don't need it in your other object.

When window is done with it and it releases the object which will get deallocated if no other object holds reference to it.

If on the other hand you keep the reference until your object is deallocated then the object will hang around until your object is deallocated.

If you don't need it then release right away.

By the way the correct way to create and instance is to call:

Obj * o = [[Object alloc] init]

Alloc allocates memory, init (or any other init... methods) initializes the object (I believe).

stefanB
Thanks,I'm calling an initWithFrame in my code actually....didn't list it here for purpose of brevity and focus. Sorry if it was confusing ;)
Spanky
+1  A: 

If the object is only used by that method, then it should be a local variable and released in that method (as in the second example). If it's a property of the class that other methods use, it should be stored in an instance variable and released when the owning object goes away (as in the second example).

Chuck
Right, but what about memory or perf implications to either method? That's what I'm trying to figure out. Sorry if I wasn't clear :)
Spanky