How to initialize a custom class / object in the controller using Objective-C on Iphone

I have a simple "model" class, for example (complete with constructor, of course)

@implementation Widget @synthesize name; @synthesize color; - (id) init { if (self = [super init]) { self.name = @"Default Name"; self.color = @"brown"; } return self; } @end 

I declared it an internal member of my controller as follows:

 #import <UIKit/UIKit.h> #import "Widget.h" @interface testerViewController : UIViewController { IBOutlet UITextField *stuffField; Widget *widget; } @property (nonatomic, retain) UITextField *stuffField; @property (nonatomic, retain) Widget *widget; - (IBAction)buttonPressed:(id)sender; @end 

and ... I'm trying to initialize it inside my controller as follows:

 #import "testerViewController.h" @implementation testerViewController @synthesize stuffField; @synthesize widget; - (IBAction)buttonPressed:(id)sender { stuffField.text = widget.name; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { widget = [[Widget alloc] init]; } return self; } 

but .. it does not seem to initialize my object because my text field becomes empty every time. Any clues?

+6
cocoa-touch
source share
1 answer

Try using

- (void) viewDidLoad {} method to initialize your data

in your interface class use @class Widget instead of #import "Widget.h"

and in your implementation class use #import "Widget.h"

and make sure you are logged into your buttonPressed handler!

+4
source share

All Articles