简体   繁体   English

先前的问题:从Appdelegate访问另一个类中的UILabel

[英]Previously asked: Accessing UILabel in another class from Appdelegate

I have a method that that subtracts 2 from an int "healthInt". 我有一个从int“ healthInt”减去2的方法。 Then after that i have an NSString called "healthString" which will just display "healthInt". 然后,在那之后,我有一个名为“ healthString”的NSString,它将仅显示“ healthInt”。 So what I wanna do in this method "take2Damage" is subtract 2 from "healthInt". 因此,我想在“ take2Damage”方法中从“ healthInt”中减去2。 then set a UILabel called "healthLabel" to healthString. 然后将一个名为“ healthLabel”的UILabel设置为healthString。 the problem is healthLabel is located in another class. 问题是healthLabel位于另一个类中。 Here's some code. 这是一些代码。

Appdelegate.m

-(void)take2Damage{
healthInt = healthInt - 2;

}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:        (NSDictionary *)launchOptions
{
healthInt = 100;
healthString = [[NSString alloc]initWithFormat:@"%d", healthInt];

LevelOneViewController.m

IBOutlet UILabel * healthLabel;

Since the last person didn't know what i meant, i thought i'd clarify. 由于最后一个人不知道我的意思,所以我想澄清一下。 I want code that i can put in the take2Damage to access a UILabel from another class. 我想要可以放入take2Damage中的代码从另一个类访问UILabel。 If that isn't possible then i would like code to access the healthInt variable from another file. 如果那不可能,那么我想代码从另一个文件访问healthInt变量。 Hopefully this will work thanks. 希望这会工作谢谢。

First, do not modify the IBOutlets of another class. 首先,不要修改另一个类的IBOutlets。 This is very error prone because of how IBOutlets are managed by UIViewController . 由于UIViewController是如何管理IBOutlet的,因此这很容易出错。

Next, your basic issue is that you're not following the MVC pattern (Model-View-Controller). 接下来,您的基本问题是您没有遵循MVC模式(模型-视图-控制器)。 Something like "health" should be stored in a model object such as a "Player" class. 诸如“健康”之类的东西应存储在模型对象中,例如“ Player”类。 The AppDelegate does not take damage. AppDelegate不会受到损坏。 The Player takes damage. 玩家受到伤害。 Then the view displays the current value of player.health . 然后,视图显示player.health的当前值。

To get an overview of MVC, see the Cocoa Core Competencies docs (be sure to follow the links). 要获得MVC的概述,请参阅Cocoa核心能力文档(请确保遵循链接)。 MVC is the heart of Cocoa development. MVC是可可开发的核心。 Make sure you understand it before going too far. 确保您了解它,然后再走太远。

Also useful: Organizing iOS project for MVC design pattern 也有用: 组织用于MVC设计模式的iOS项目

And some good example code showing a well-designed MVC app: The Elements . 还有一些很好的示例代码,展示了一个精心设计的MVC应用: The Elements

You will probably have further questions after you read the above, but start by reading up on the basic architecture of Cocoa. 阅读以上内容后,您可能还会有其他问题,但请先阅读可可的基本架构。 Then it should be more clear how objects interact with each other. 然后,应该更加清楚对象之间如何交互。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM