Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Call NSUserDefault Value To Another View Controller?

// 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.

like image 518
Peer Mohamed Thabib Avatar asked Jan 28 '26 20:01

Peer Mohamed Thabib


2 Answers

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);
    }
like image 142
Dharmbir Singh Avatar answered Jan 31 '26 10:01

Dharmbir Singh


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);
    }
like image 29
iphondroid Avatar answered Jan 31 '26 09:01

iphondroid