Search code examples
iosobjective-cmemory-managementretain

Memory management, things to be clear


I need to get things clear about Objective-C memory management:

If I declare an object in the class header as ivar without @property:

 @interface MyFacebooDelegate : UIViewController 
 {
     TableViewController *tableController;
 }
 ...
 @end

and some where in the code for example in - (void)viewDidLoad I do :

tableController = [[TableViewController alloc] init];

so where is best way to release it. What if I make the instant object a property what will be the different? and how the memory management will be too

@interface MyFacebooDelegate : UIViewController 
 {
     TableViewController *tableController;
 }
 ...
 @end
@property (nonatomic, strong) TableViewController *tableController;

What the following syntax do exactly for the object viewController:

.h

 @interface AppDelegate : UIResponder <UIApplicationDelegate>
 @property (strong, nonatomic) ViewController *viewController;
 @end 

.m

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;

- (void)dealloc
{
  [_window release];
  [_viewController release];
  [super dealloc];
}
.....
@end

If I want to return an object through a method to another class, do I need to autorelease it in the method body first and then retain it in receiver side? for example this method what exactly to do in the method body and in the receiver side too:

-(NSString *)getFriendId
 {
NSArray *ar = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];
return [ar objectAtIndex:0];
 }

I know this a lot but I am really confused and need your help.


Solution

  • 1) best way is in dealloc; or right before re-setting it.

    2) a property does the retain/release for you. But WARNING! You keep mixing up things. You use "strong" here, which relates to ARC. If you really insist on using classic retain/release (you shouldn't) then use (nonatomic, retain) instead.

    3) Your properties get deallocated on dealloc. Again, strong is wrong here.

    4) Yes. Ideally you should. Another reason why ARC is awesome, it does this all for you, automatically.

    tl;dr: Use ARC. Never go back. (But still learn manual memory management)