如何使用Iphone上的Objective-C在控制器中初始化自定义类/对象

Dav*_*ave 6 cocoa-touch

我有一个像这样的简单"模型"类(当然还有构造函数)

@implementation Widget
@synthesize name;
@synthesize color;

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

@end
Run Code Online (Sandbox Code Playgroud)

我已经将它声明为我的控制器的内部成员,如下所示:

#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
Run Code Online (Sandbox Code Playgroud)

并且......我正试图在我的控制器中初始化它,如下所示:

#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;
}
Run Code Online (Sandbox Code Playgroud)

但是......它似乎没有初始化我的对象,因为我的文本字段每次都显示为空白.有线索吗?

And*_*obs 4

尝试使用

-(void) viewDidLoad{} 方法来初始化您的数据

在您的界面类中使用 @class Widget 而不是 #import "Widget.h"

并在您的实现类中使用#import“Widget.h”

并确保您进入您的buttonPressed处理程序!