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/