I am confused in some condition when I have to release an object? So I wants to know when we release objects in objective C. Can I use autorelease where I alloc the objects any disadvantage of autorelease? Where release the following objects?
Case 1:
SelectFrame *obj=[[SelectFrame alloc]initWithNibName:@"SelectFrame" bundle:nil];
[[self navigationController] pushViewController:obj animated:YES];
Case 2:
UIView *barView=[[UIView alloc]initWithFrame:CGRectMake(0, 500, 200,50)];
barView.backgroundColor=[UIColor redColor];
[self.view addSubview:barView];
Case 3:
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:@"https://xxxxxxxxxxxxxxxxx"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
Yes, you have to release for the Above two cases.
Case 1:
Case 2:
Case 3:
You don’t need a release here, as the request object is in autoreleased mode.
Remember two things.
1.) You have to manually release an object when you
retainoralloc-initthat object.2.) Class methods which do not have alloc methods return an
autoreleasedobject hence you don’t need to release those objects.Disadvantage of using
autorelease:Ok, so what does
autoreleasemean? Autorelease means , not us, but our App would decide when to release the object. Supposing case 2 of your question. AfterbarViewis added toself.viewthere is no need of this allocated object. Hence, we release it. But, if we had kept it inautoreleasemode, the App would keep it for longer time, wasting some part of memory by still keeping that object. Hence, we shouldn’t use autorelease here.Advantage of using
autorelease:This over-popular example.
Here, the 3rd line causes a leak because we do not release the memory allocated to
myText.Hence,
SOLUTION
Use ARC, forget
retainrelease🙂