首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Xcode中用一个简单的按钮调用另一个类中的方法

如何在Xcode中用一个简单的按钮调用另一个类中的方法
EN

Stack Overflow用户
提问于 2012-06-12 23:02:45
回答 2查看 5.6K关注 0票数 0

我试图用我的故事板中的一个简单按钮从另一个类调用一个方法。以下是我的文件:

ViewController.m

代码语言:javascript
运行
复制
//  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

代码语言:javascript
运行
复制
//  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

代码语言:javascript
运行
复制
//  PrintHello.h
#import <Foundation/Foundation.h>

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

PrintHello.m

// PrintHello.m

代码语言:javascript
运行
复制
#import "PrintHello.h"
@implementation PrintHello 

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

@end

此外,在storyBoard中,还有一个与Viecontroller相关联的Button01。从日志中我知道:

加载viewDidLoad并在按下时按下按钮:)但未调用Print方法?

我哪里做错了?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-06-12 23:09:10

在你调用[self.printMessage Print];之前,我想你需要把self.printMessage = [[PrintHello alloc] init];

票数 1
EN

Stack Overflow用户

发布于 2012-06-12 23:13:21

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

代码语言:javascript
运行
复制
-(void)viewDidLoad
{
    [super viewDidLoad];
    self.printMessage = [[PrintHello alloc] init];
    NSLog(@"ViewDidLoad loaded");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10999371

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档