3

// 我在单独的类文件中写了这个函数:

-(void)Display
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSInteger *Position = [prefs integerForKey:@"currentlevel"];
    NSLog(@"------->%i",Position);
    //This NSLog is returning Value 6  
    [prefs synchronize];    
}

//在我的viewController我使用我为我的类创建的对象调用这个函数

@interface ViewController ()
{
    //display My class name
    //disp is object fro my class
    display *disp;   
}

@implementation ViewController

- (void)viewDidLoad
{ 
    disp = [[display alloc]init];  
    [disp Display];
    NSLog(@"%i",[disp Position]);
    //this NSLog statement returning value 0
    [super viewDidLoad];
}

如果有人有任何解决方案,请帮助我。

4

3 回答 3

3

尝试像这样实现..

@implementation ClassA

      - (void)viewDidLoad
        {
            [super viewDidLoad];
            // Do any additional setup after loading the view, typically from a nib.
            [[NSUserDefaults standardUserDefaults]setInteger:100 forKey:@"currentlevel"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }

    @end

    @implementation ClassB

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
           int B = [[[NSUserDefaults standardUserDefaults] integerForKey:@"currentlevel"] integerValue];

         NSLog(@"Interger Value %d",b);
    }
于 2013-07-19T11:18:38.320 回答
1

如果要设置整数值,请使用以下语句:

[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:highScore] forKey:@"kHighScore"];

如果您想取回该值,请使用以下语句:

NSInteger highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"kHighScore"] intValue];
于 2013-07-19T12:27:54.357 回答
1

为什么不从视图控制器本身的 NSUserDefaults 中获取值?像这样:

    -(void) viewDidLoad
    {
      [super viewDidLoad];
      NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
      NSInteger *Position = [prefs integerForKey:@"currentlevel"];
      NSLog(@"------->%i",Position);
    }
于 2013-07-19T12:17:34.027 回答