Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/38.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
Iphone 从AppDelegate.m中的另一个类访问UILabel_Iphone_Objective C_Ios - Fatal编程技术网

Iphone 从AppDelegate.m中的另一个类访问UILabel

Iphone 从AppDelegate.m中的另一个类访问UILabel,iphone,objective-c,ios,Iphone,Objective C,Ios,我有一个从inthealthInt中减去2的方法。然后,我有一个名为healthString的NSString,它将只显示healthInt。所以在这个方法中我想做的是从healthInt中减去2。当将名为healthLabel的UILabel设置为healthString时。问题是healthLabel位于另一个类中。这里有一些代码 Appdelegate.m -(void)take2Damage{ healthInt = healthInt - 2; } - (BOOL)applicat

我有一个从
int
healthInt
中减去2的方法。然后,我有一个名为
healthString
NSString
,它将只显示
healthInt
。所以在这个方法中我想做的是从
healthInt
中减去2。当将名为
healthLabel
UILabel
设置为
healthString
时。问题是
healthLabel
位于另一个类中。这里有一些代码

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;

您的设计不尽如人意,但您可以这样做:

self.healthLabel = (YourAppDelegate *)[[[UIApplication sharedApplication] delegate] healthString];
但我要再次强调的是,要改变您的设计,不要依赖appDelegate中发生的此类事情。考虑使用单态状态,这将是更好的,同时保持简单。

编辑:

更清楚地说,这就是我如何理解你们目前的情况。在
AppDelegate
类中,您已将
healthInt
healthLabel
定义为属性和
-(void)take2Damage
healthInt
存储玩家的健康,
healthLabel
是该健康的用户友好字符串,
take2Damage
healthInt
中减去两个伤害

您还有另一个类,您想从中访问
healthInt
healthString
take2Damage
。让我们调用该类
GameViewController
。因此,在
GameViewController
中相关的任何方法中,您都应该使用上述代码

请注意,您必须在
GameViewController
.h
文件中导入AppDelegate.h

这绝对没有理由不起作用。只要您在
AppDelegate
中定义了如下属性:

@property(非原子,赋值)NSInteger-healthInt
@property(非原子,保留)NSString*healthString
-(void)接受2损坏

把它们综合起来,你应该表现得很好


祝你好运

那么我应该把它放在“take2damage”方法中吗?不,你不能把它放在
take2damage
方法中。实际上,你把它放在任何一个你调用它的类中。另外,我为试图帮助你而道歉:-)祝你好运,我的朋友。对不起,我没有生气。我一整天都在做这件事,所以我真的很沮丧。不管怎样,谢谢。嘿,我也不是,但我想退一步,看看你在这里做什么,你会受益匪浅。首先,我提供的代码可以满足您的预期目的。其次,这是一个糟糕的代码。如果您必须使用单例,并且对于游戏来说它可能是合适的,那么您应该有一个
状态
单例,它采用最简单的设计,可以存放您需要访问的所有内容。但请阅读以下内容:你会发现这些建议很有帮助,我是这么做的。我试着把它们放进去,但is建议用它代替。我使用->并且当我这样做时,它会给我更多的错误。我把它放在一个单独的类中的方法中。另一个问题是,当我把它放在一个单独类的方法中时,我无法访问委托中的healthInt。