在整个应用程序中使用 1 个变量,我在哪里初始化它?
我有一个应用程序,第一页上有一个按钮,用户可以设置第二页上的图像。 要切换页面,我使用的代码是:
- (IBAction)myCart:(id)sender; {
MyCartViewController * cart2 = [[MyCartViewController alloc]init];
cart2.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:cart2 animated:YES];
[cart2 release];
}
我还有另一种方法,允许用户按下按钮并设置图像。
- (IBAction)outlet1 {
cart.displayImage = YES;
}
cart 是在 .h 文件中创建的 ivar,因此我可以在整个文件中使用它。我的问题是我需要能够在 myCart 方法中使用 cart (不是 cart2)。我该怎么做?因为如果我尝试将 cart2 与 cart 进行切换,并且删除该行: MyCartViewController * cart2 = [[MyCartViewController alloc]init];
当我尝试切换页面时,应用程序崩溃。我如何为这两种方法使用相同的变量?谢谢大家!
I have an app and on the first page is a button that the user can set an image which is on the second page.
To switch pages, the code im using is:
- (IBAction)myCart:(id)sender; {
MyCartViewController * cart2 = [[MyCartViewController alloc]init];
cart2.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:cart2 animated:YES];
[cart2 release];
}
And i also have another method this allows the user to press a button and set an image.
- (IBAction)outlet1 {
cart.displayImage = YES;
}
cart is a ivar created in the .h file so i can use it through out the whole file. My problem is that i need to be able to use cart (not cart2) in the myCart method. How can i do this? Because if i try to swtich the cart2's with just cart and i delete the line:MyCartViewController * cart2 = [[MyCartViewController alloc]init];
the app crashes when i try to switch pages. How can i use the same variable for both methods? Thanks everybody!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
cart2
是本地引用变量,无法在myCart
方法之外持续存在。相反,将其声明为接口变量的一部分,并在init
方法中对其进行初始化。不要忘记在释放所有接口成员变量的最后释放它(在dealloc中)。cart2
is local reference variable and can not persist beyond the methodmyCart
. Instead declare it as a part of interface variable and initialize it in theinit
method. Don't forget to release it finally at the end where you are releasing all interface member variables ( indealloc
).