3

// I wrote this function in Separate class file:

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

//In my viewController I am calling this function using object I have created for my class

@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];
}

If anyone has any solution please help me.

Walery Strauch
  • 6,792
  • 8
  • 50
  • 57
Peer Mohamed Thabib
  • 636
  • 2
  • 9
  • 29

3 Answers3

3

Try to implement like this..

@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);
    }
Dharmbir Singh
  • 17,485
  • 5
  • 50
  • 66
1

Why not get the value from NSUserDefaults in the view controller itself? Like this:

    -(void) viewDidLoad
    {
      [super viewDidLoad];
      NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
      NSInteger *Position = [prefs integerForKey:@"currentlevel"];
      NSLog(@"------->%i",Position);
    }
iphondroid
  • 498
  • 7
  • 19
1

If you want to set an integer value then use this statement:

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

If you want to get that value back then use this statement:

NSInteger highScore = [[[NSUserDefaults standardUserDefaults] objectForKey:@"kHighScore"] intValue];
andrewsi
  • 10,807
  • 132
  • 35
  • 51
Mital
  • 241
  • 1
  • 5