在我的项目中,我在FirstViewController中声明了一个BOOL * isOn。在FirstViewController中,我有两个按钮,按下buttonOne,将isOn设置为YES,buttonTwo设置isOn为NO。在我的SecondViewController中,我正在尝试运行一个引用isOn状态的if语句。我收到错误“分配给'readonly'不允许返回Objective-C的结果”。我怎么能得到我想要的意图?
//FirstViewController.h
@property (assign) BOOL isOn;
- (IBAction)buttonOne:(id)sender;
- (IBAction)buttonTwo:(id)sender;
//FirstViewController.m
- (IBAction)buttonOne:(id)sender {
[self setIsOn:YES];
}
- (IBAction)offSiteButton:(id)sender {
[self setIsOn:NO];
}
//SecondViewController.m
#import "FirstViewController.h"
#import "FirstViewController.m"
FirstViewController *FVC
- (void)viewDidLoad {
if ([FVC isOn] = YES) { <----Error
// Do this
} else {
// Do that
}
如果我只是用...运行它
if ([FVS isOn])
if语句返回else函数,并为两个按钮执行'does that'。请帮忙。
答案 0 :(得分:4)
编译错误是因为你忘记了一个等号,它应该是
if ([FVC isOn] == YES)
尽管如此,[FVS isOn]
与此相同,所以只运行Do that
的问题并不存在。没有足够的代码来弄清楚为什么会发生这种情况:你确定FVC已被设置为正确的值吗?
答案 1 :(得分:1)
尝试: if(FVC.isOn == YES) 请记住,当您想要比较使用==运算符的值时。
答案 2 :(得分:0)
如果您使用的是故事板,则可以使用
将值从第一个视图控制器传递给secondViewController ViewController中的:h
#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ():UIViewController
@property (nonatomic) BOOL isOn;
-(IBAction)button:(UIButton *) button;
-(IBAction)go;
@end
在ViewController.m中
@implementation ViewController
@synthesize isOn;
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
SecondViewController *vc = [segue destinationViewController];
[vc setIsOn:isOn];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)button:(UIButton *)button
{
switch (button.tag) {
case 1:
[self setIsOn:YES];
break;
case 2:
[self setIsOn:NO];
break;
}
}
-(IBAction)go
{
[self performSegueWithIdentifier:@"next" sender:nil];
}
并在SecondViewController.h中
@interface SecondViewController : UIViewController
@property (nonatomic) BOOL isOn;
@end
在SecondViewController.m中
@implementation SecondViewController
@synthesize isOn;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
if (isOn == YES)
{
NSLog(@"Hello");
}
else
{
NSLog(@"exit");
}
}