ios - 按下按钮时在类中使用数据 Objective-C/iOS

标签 ios objective-c

iOS 的新手,我搞不懂这个简单的事情。 (谷歌搜索了很久)

所以我有一个在 ViewController.m viewDidLoad 中启动的类,

Student *person = [[Student alloc] init];

person.firstName = @"test";

我创建了一个按钮,在按下按钮的方法上,我尝试对 firstname 变量中的任何内容进行 NSLog,但我一直得到空结果。我将初始化添加到方法中,它工作正常。

我是否可以只调用从 viewDidLoad 添加的数据?

谢谢

编辑:

@implementation ViewController

- (void) viewDidLoad
{
[super viewDidLoad];

    Student *person = [[Student alloc] init];

    person.firstName = @"test";

}

- (IBAction)buttonPressed:(id)sender {

NSLog(@"%@", person.firstName);
}
@end

最佳答案

您需要ivar 或属性(property)。例如,将 ivar 添加到您的 .m 文件中:

@implementation YOURCLASSNAME
{
    Student *person;
}

//... other code

-(void)viewDidLoad {
    person = [[Student alloc] init];

    person.firstName = @"test";
}
//... Later in the same file when the button event is called
-(IBAction)buttonTapped {
    NSLog(@"%@", person.firstName);
}

关于ios - 按下按钮时在类中使用数据 Objective-C/iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22302659/

相关文章:

ios - 我可以在 iPad 上使用哪种 UIKeyboardType

ios - UISearchBar 检测用户何时停止输入 swift

ios - Xcode 5 - 没有可见界面的 iOS 错误

iphone - 更改 UIBarButtonItem 颜色

iphone - 从 subview UIViewController Xcode 调用函数

ios - 2 个单元之间的边距

ios - AVAudioEngine 录制 AVAudioPlayerNode 中播放的声音

ios - 在锁定屏幕中使用 "open"命令打开应用程序 (iOS 8)

android - Youtube API在视频上发表评论

objective-c - 是否可以恢复我删除的 xcdatamodel 文件?