保存全局变量或类似php的会话

时间:2013-05-06 08:40:57

标签: xcode string session variables global

我正在处理我的应用,但我需要一些帮助。 在Objective C中我需要一个'类似php的会话'(不使用连接到互联网) 我考虑过全局变量,但我的应用程序似乎在重新加载视图时重置它们。 这是我目前的代码

SecondViewController.h

@interface SecondViewController : UIViewController
{
    NSString * string;
}

SecondViewController.m

@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    if (! [string isEqualToString:@"Hello"])
    {
        NSLog(@"Hello");
        string = @"Hello";
    }
    else
    {
        NSLog(@"Bye");
    }
}

@end

但每次重新加载SecondViewController时,'string'都会重置为默认值。 我正在寻找我们在php中使用的东西(a.e. $ _SESSION ['string'] ='hello')

1 个答案:

答案 0 :(得分:3)

它可能对您有所帮助。除非从您的设备中删除该应用,否则它会存储这些值。

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];

// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];

// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];

// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];

// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];

**Retrieving**

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];

// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];

// getting an Float
float myFloat = [prefs floatForKey:@"floatKey"];