Objective-c Iphone how to set default value for a property Objective-c Iphone how to set default value for a property objective-c objective-c

Objective-c Iphone how to set default value for a property


You may find it useful to read some documentation on Objective-C or Cocoa. You probably can find some good suggestions on reading material if you perform a search here in StackOverflow or on Google.

To answer your question, you should have a @implementation of CalcViewController. One would most often place this @implementation inside of the *.m file. If your *.h file is named "ViewController.h" then the implementation would go in "ViewController.m".

You would then create a copy of the UIViewController's initialization function and place it there (I don't know what the default init function is).

For example:

@implementation CalcViewController@synthesize result;@synthesize input;- (id)initWithNibName:(NSString*)aNibName bundle:(NSBundle*)aBundle{    self = [super initWithNibName:aNibName bundle:aBundle]; // The UIViewController's version of init    if (self) {        input = [[NSString alloc] initWithString:@""]; // You should create a new string as you'll want to release this in your dealloc    }    return self;}- (void)dealloc{    [input release];    [super dealloc];}@end // end of the @implementation of CalcViewController

NOTES:

  • You may want to rename the file to CalcViewController. I believe it is easier for Xcode's refactoring engine to deal with.
  • You do not need to declare the @property for the display instance variable as you connect that with Interface Builder. Unless you want clients of the CalcViewController to change it often

EDIT: April 28, 2009: 10:20 AM EST: I suggest actually allocating a NSString as you should technically release it in the dealloc.

EDIT: April 28, 2009: 11:11 AM EST: I updated the @implementation to use the UIViewController's version of init.


Very good question. The short answer is to init the values in the init function. You need to overwrite the default init function so that the default value is ready before the object can be used.I would like to suggest people stop suggesting others to read document; please answer the question directly if you can.


Another option is to write your own getter for your input property, and return @"" if the instance variable is nil. This would work even if you accidentally or intentionally assigned nil to input, whereas using init to set a default value would break.