在方法中使用变量

时间:2018-07-11 08:38:13

标签: ios objective-c xcode variables

再次,我对目标c和Xcode还是陌生的。我正在构建一个小型应用程序,需要在“方法”中使用变量。我不知道将其放在哪里,因此可以在“方法”中使用它。

我有一个按钮可以启动整个过程,但是此按钮的Method需要一个变量,该变量只应创建一次(因为它是一个随机数)并保存,以便“ Button Method”可以使用它进行比较。在哪里放置它,以便我的方法可以使用它时变量保持不变?

Thx

- (IBAction)guessButton:(id)sender { 
    NSLog(@"Answer = %i", answer); 
    NSLog(@"Button Pressed"); 
    float guess = [[self.guessTextField text] floatValue]; 
    NSLog(@"Guess = %f", guess); 
}

2 个答案:

答案 0 :(得分:0)

像这样在.h文件中创建...。

#import <UIKit/UIKit.h>
@interface GoogleMapsViewController : UIViewController
@property int answer;//If it's int. Here mention your variable type(If it string @Property NSString * answer;)
@end

然后通过self.answer

致电
- (IBAction)guessButton:(id)sender { 
    NSLog(@"Answer = %i", self.answer); 
    NSLog(@"Button Pressed"); 
    float guess = [[self.guessTextField text] floatValue]; 
    NSLog(@"Guess = %f", guess); 
}

enter image description here

答案 1 :(得分:0)

建议将私有变量存储在实现类中。我们可以像这样在.m文件中定义变量

@interface ViewController (){
    NSString *stringTodefineAge;
}

@property (readonly, strong, nonatomic) ModelController *modelController;
@end

@implementation RootViewController
....