Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/116.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios uiviewcontroller alloc在访问时更改setter/getter值?_Ios_Objective C_Cocoa Touch_Setter_Init - Fatal编程技术网

Ios uiviewcontroller alloc在访问时更改setter/getter值?

Ios uiviewcontroller alloc在访问时更改setter/getter值?,ios,objective-c,cocoa-touch,setter,init,Ios,Objective C,Cocoa Touch,Setter,Init,好吧,我一直在想办法,但我不知道。。。基本上,我的ios应用程序中有两个类,第一个是我的主视图,第二个是存储一些变量的类。我有一个开关,当开关的状态改变时,它将另一个类中的布尔getter/setter变量设置为该状态。然后我得到值并将其打印在日志中。但是我注意到,每次调用viewcontroller时,都会使用以下代码: StoredVars *stored = [[StoredVars alloc]init]; 该值默认为0。。。为了显示这一点,我添加了viewcontroller调用的

好吧,我一直在想办法,但我不知道。。。基本上,我的ios应用程序中有两个类,第一个是我的主视图,第二个是存储一些变量的类。我有一个开关,当开关的状态改变时,它将另一个类中的布尔getter/setter变量设置为该状态。然后我得到值并将其打印在日志中。但是我注意到,每次调用viewcontroller时,都会使用以下代码:

StoredVars *stored = [[StoredVars alloc]init]; 
该值默认为0。。。为了显示这一点,我添加了viewcontroller调用的第二个实例,两个日志调用打印出不同的值。Switchy是第二类“StoredVars”中的bool setter/getter。有人能解释一下为什么会这样吗?下面是我第一个类的.m文件中的代码:

StoredVars *stored = [[StoredVars alloc]init];
[stored setSwitchy:(_toggle.on)];
NSLog(@"%d", [stored switchy]);
StoredVars *stored2 = [[StoredVars alloc]init];
NSLog(@"%d", [stored2 switchy]);
如果我打开开关,第一个日志打印1,第二个日志打印0。如果我关闭开关,它们都会打印0

谢谢大家:)

这一行

StoredVars *stored = [[StoredVars alloc]init];
正在销毁先前存储在
stored
变量中的内容,并创建一个全新的对象,换句话说,每次调用此行时,“store”的先前内容都会被销毁。您只需要初始化它一次(可能在ViewController的
init
方法中),然后继续使用它而不重新初始化它

[stored setSwitchy:(_toggle.on)];

二传手和接球手是这样的:

    - (void)setSwitchy:(BOOL)bSwitchy
    {

       _bSwitchy = bSwitchy;
    }

    - (BOOL)switchy
    {

       return _bSwitchy;
    }
因此,setter中的属性值正在更改。 第二个打印一个0,即您没有调用setter,那么getter将重新运行默认值


顺便说一下,stored和stored2是两个对象。

我知道您有两个ViewController

因此,我将它们称为开关所在的Viewcontroller。 和另一个想要切换效果的ViewController

1) 在Viewcontroller中,开关值更改时>放置此代码

 AnotherViewController *anotherVc=[[AnotherViewController alloc]init];
    [anotherVc setToggle:sw];  //sw will be your switch changed value.
2) 在另一个视图控制器.h文件中

 @interface AnotherViewController : UIViewController
{
      int  _toggle;

}
@property(nonatomic,assign)int toggle;
3) 综合开关 在另一个ViewController.m文件中

   -(void)setToggle:(int)toggle1{
    toggle=toggle1;
}
4) 将在视图中或任何位置显示 你可以查一下

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:YES];

    if(toggle)
        swithlbl.text=@"YES";
    else
        swithlbl.text=@"NO";
}

问题是我需要从多个类中访问“存储”变量,而不会破坏该值。这就是我的观点!每次调用“init”都是在破坏它,所以不要使用它!(仅在您的程序开始时使用)您能给我一个示例,说明我将如何进行声明吗?我对它不太熟悉…这是非常基本的信息,如果你还不了解我的话,我建议你阅读一本教程,同时也阅读基本的Objective-C语言。