Memory Management in Iphone. Lazy Initialization
I just started programming in Objective-C. Prior to this I was primarily a C# person.
Please let me know where if I release the memory in the following code in a correct manner.
@implementation CalculatorViewController
-(CalculatorBrain *) brain
{
if(!brain)
{
brain = [[CalculatorBrain alloc] init];
}
return brain;
}
-(IBAction) operationPressed: (UIButton *) sender
{
NSString *operation = sender.titleLabel.text;
if(userInMiddleOfTypingDigit)
{
[self brain].operand = display.text.doubleValue;
userInMiddleOfTypingDigit = NO;
}
double result = [[self brain] performOpeaation:operation];
[display setText:[NSString stringWithFormat:@"%g",result]];
}
- (void)dealloc
{
[brain release];
[super dealloc];
}
Basically I am doing lazy initialization as shown in Stanford university tutorial. But not sure if I am releasing memory correctly.
Please correct me if there开发者_StackOverflow社区 is something wrong.
Thanks,
Yes, that looks fine. For that matter, instead of this:
[self brain].operand = display.text.doubleValue;
you could also do this:
self.brain.operand = display.text.doubleValue;
They're exactly equivalent. Some people like the dot syntax, some don't. But where you were already using it in one place, you may as well be consistent.
Note that if you plan on this class being accessed by multiple threads, then you would want to protect the lazy initialization check from synchronization issues. But that's outside the scope of this question, I think. Your memory management is fine.
精彩评论