Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Initialize custom class/object within controller using Objective-C on the Iphone

Tags:

cocoa-touch

I've got a simple "model" class like so (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've declared it as an internal member to my controller like so:

#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 within my controller like so:

#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 doesn't seem to be initializing my object because my textfield comes up blank every time. Any clues?

like image 706
Dave Avatar asked Mar 13 '09 08:03

Dave


1 Answers

Try to use

-(void) viewDidLoad{} method to initiliaze 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 come into your buttonPressed handler!

like image 70
Andy Jacobs Avatar answered Oct 19 '22 07:10

Andy Jacobs