我正在为 iOS 制作一款游戏,其中包含每个级别的评分系统。在这里,我有一些通过使用委托获得NSString
( ) 的代码。passedValue1
这是委托的代码:
LevelCompleteLevel1
。H
#import "ViewController.h"
@interface LevelCompleteLevel1 : UIViewController{
IBOutlet UILabel *label;
ViewController *secondviewData;
}
@property (nonatomic, retain)ViewController*secondviewData;
.m
ViewController *second = [[ViewController alloc] initWithNibName:nil bundle:nil];
self.secondviewData = second;
secondviewData.passedValue1 = label.text;
[self presentModalViewController:second animated:YES];
在.m
我将当前标签中的一个值发送viewcontroller
到另一个view controller
我发送的值被称为passedValue1
一旦我发送了我需要显示的值并保存在我的ViewController
ViewController
。H
@interface ViewController : UIViewController{
IBOutlet UILabel *label;
NSString *passedValue1;
}
@property (nonatomic, retain)NSString *passedValue1;
@end
.m
首先我...@synthesize passedValue1;
然后我添加代码以接收我的值viewDidLoad
并将我的值显示在UILabel
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
NSString *key=@"labelKey";
// Do any additional setup after loading the view, typically from a nib
if(passedValue1){
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSObject * object = [prefs objectForKey:key];
if(object != nil){
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
[defults setObject:passedValue1 forKey:key];
[defults synchronize];
}
else{
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
NSInteger readScore=[[[NSUserDefaults standardUserDefaults] objectForKey:key] integerValue];
NSInteger newValue=readScore+[passedValue1 integerValue];
[defults setObject:[NSString stringWithFormat:@"%d",newValue] forKey:key];
[defults synchronize];
}
}
label.text = [[NSUserDefaults standardUserDefaults]objectForKey:key];
}
一旦我显示了值,我就使用NSUserDefault
. 但是,一旦我重玩了我的游戏并获得了另一个得分值,我想将新passedValue1
值添加到当前保存的值中......
例如:
假设我玩了我的关卡,我得到了 10 的得分值。然后保存该值并重播我的关卡。然后我想获取保存的值并将其添加到我刚刚得分的值中。所以这就是说我得分的第二个值是 20。然后我希望我的代码将它们加在一起并给我一个 30 的值。
任何人都可以帮忙,因为我正在使用的代码没有正确执行我想要执行的功能,即添加上一个和当前传递的值。
提前致谢。
使用此代码编辑 Iam:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
NSString *key=@"labelKey";
// Do any additional setup after loading the view, typically from a nib
if(passedValue1){
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSObject * object = [prefs objectForKey:key];
if(object != nil){
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
[defults setObject:passedValue1 forKey:key];
[defults synchronize];
}
else{
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
NSInteger readScore=[[[NSUserDefaults standardUserDefaults] objectForKey:key] integerValue];
NSInteger newValue=readScore+[passedValue1 integerValue];
[defults setValue:[NSString stringWithFormat:@"%d",newValue] forKey:key];
[defults synchronize];
}
}
label.text = [[NSUserDefaults standardUserDefaults]objectForKey:key];
}
为什么这不起作用,标签的显示值是最初传递的Value1?