0

我正在尝试使用情节提要中的一个简单按钮从另一个类调用方法。这是我的文件:

视图控制器.m

//  ViewController.h


#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "PrintHello.h"

@interface ViewController : UIViewController <NSObject>{

PrintHello *printMessage;
}

@property (nonatomic, retain) PrintHello *printMessage;
@end

视图控制器.m

//  ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end

@implementation ViewController
@synthesize printMessage;


- (void)viewDidLoad{
[super viewDidLoad];
NSLog(@"ViewDidLoad loaded");
}


- (IBAction)Button01:(id)sender{

self.printMessage = [[PrintHello alloc] init]; // EDIT: THIS LINE WAS MISSING NOW IT WORKS

[self.printMessage Print];
NSLog(@"Button01 Pressed");    
}
@end

打印你好.h

//  PrintHello.h
#import <Foundation/Foundation.h>

@interface PrintHello : NSObject
-(void) Print;
@end

打印你好.m

// 打印你好.m

#import "PrintHello.h"
@implementation PrintHello 

-(void)Print{ NSLog(@"Printed");}

@end

而且在storyBoard 中还有一个Button01 链接到Viecontroller。从日志中我知道:

加载 viewDidLoad 并在按下按钮时按下按钮:) 但是方法 Print 没有被调用?

我在哪里做错了?

4

2 回答 2

1

在你打电话之前[self.printMessage Print];,我认为你需要把self.printMessage = [[PrintHello alloc] init];

于 2012-06-12T15:09:10.260 回答
0

正如 woz 所说,您还没有初始化 printMessage,所以该对象还不存在!您可能希望在 ViewController.m 文件的 viewDidLoad 中对其进行初始化,而不是在单击按钮时一遍又一遍地重新初始化对象。

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.printMessage = [[PrintHello alloc] init];
    NSLog(@"ViewDidLoad loaded");
}
于 2012-06-12T15:13:21.197 回答