0

ストーリーボードの単純なボタンを使用して、別のクラスからメソッドを呼び出そうとしています。ここに私のファイルがあります:

ViewController.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

ViewController.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

PrintHello.h

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

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

PrintHello.m

// PrintHello.m

#import "PrintHello.h"
@implementation PrintHello 

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

@end

また、storyBoard には、Viecontroller にリンクされた Button01 があります。ログから私はそれを知っています:

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 に答える