I have a beginner's question. I would like to have access to an UIView in all parts of my code (as opposed to a single method/function).
I therefore declared it in the @interface section
UIView *calendarView;
and then @property (nonatomic, retain) UIView *calendarView
. In the @implementation I have @synthesise calendarView
.
Now I would like to define the frame of this view and coded the following:
CGRect calendarFrame = CGRectMake(170, 8, 200, 50);
calendarView = [[UIView alloc] initWithFrame:calendarFrame];
But I am now wondering if I am doing something seriously wrong here, as calendarView has already been retained and synthesised. Surely UIView alloc is superfluous or even bound to make the app crash, as I am running into memory problems, right?
So I though I should code this instead of the two previous lines, but it only had the effect that the calendarView is not shown at all:
[calendarView setFrame:CGRectMake(170, 8, 200, 50)];
So my question is if I really need to alloc the view before I can use it? Or is there yet another solution?
you can retain an object only after you have it in memory(ie you have alloc'ed it)..So below given code is correct and needed..
CGRect calendarFrame = CGRectMake(170, 8, 200, 50);
calendarView = [[UIView alloc] initWithFrame:calendarFrame];//you have alloc'ed once
now you will add this view to a parentView. For example I am inside a UIViewController implementation..
[self.view addSubView:calendarView]; //now only your retain takes place. //So now calenderView has to release twice..Once by you (since you alloced it) and once by viewcontroller (since it has retained it)...
[calendarView release];//we are releasing once but the object will not be removed from memory since it is retained by viewController..Our part in memory management is over..Now when this viewController get dealloced it releases
You can use this calendarView throughout the implementation of this UIViewController..
-(void)dealloc{
[super dealloc];//should be last in dealloc..Now the entire controller will be dealloced along with the calenderView which is retained by viewController and the memory will be freed for future uses..
}
These are some useful tutorials..easier to understand than apple's documentation..But read Apple's documentation too..
http://ferasferas.wordpress.com/2010/12/05/introduction-to-memory-management-on-iphone/
http://iosdevelopertips.com/objective-c/memory-management.html
http://mauvilasoftware.com/iphone_software_development/2008/01/iphone-memory-management-a-bri.html
https://humblecoder.blogspot.com/2009/08/iphone-tutorial-memory-management.html