将字符串保存到NSUserDefaults吗?


Answers:


449
NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];

以后再拿回来

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"preferenceName"];

1
有什么办法可以在特定日期保存此字符串?谢谢,但是您的代码与我的代码相同,我创建了一个自定义日历应用程序,用户可以在其中编写自己的笔记,例如,2月3日,用户编写了一些内容,此文本应在2月3日保存,然后当用户移至另一个天,他/她还可以根据当天的日期写一些其他内容
Mc.Lover 2012年

6
由于某种原因,直到我调用了sync方法,保存部分才能正常工作。 NSString *valueToSave = @"someValue";[[NSUserDefaults standardUserDefaults]setObject:valueToSave forKey:@"preferenceName"]; [[NSUserDefaults standardUserDefaults]synchronize
fs_tigre 2014年

5
[[NSUserDefaults standardUserDefaults]同步];正在被弃用
Juan Boero

49

更确切地说

-(void)saveToUserDefaults:(NSString*)myString
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

    if (standardUserDefaults) {
        [standardUserDefaults setObject:myString forKey:@"timestamps"];
        [standardUserDefaults synchronize];
    }
}

11
无需对standardUserDefaults对象执行nil检查。在Objective-C中将消息发送为nil非常好。
jbrennan

12
但更重要的是,他包括“同步”-如果您不调用NSUserDefaults,它将非常不稳定!
PostCodeism 2010年

1
standardUserDefaults为我同步修复了一些奇怪的错误,谢谢!
Scott Roepnack 2012年

1
该参考文献讨论了该synchronize方法:“仅当您无法等待自动同步时才使用此方法(例如,如果您的应用程序将要退出)”- NSUserDefaults类参考
eliocs 2013年

@jbrennan虽然您的评论在技术上是正确的,但是如果您正在写重要的东西并希望确保已成功保存,则此答案很有用。此外,就此而言,最好测试(而不是忽略)的返回值synchronize。该文档说:如果数据已成功保存到磁盘,则为YES,否则为NO。
罗勒·布尔克

31

使用Swift的方法如下:

var valueToSave = "someValue"
NSUserDefaults.standardUserDefaults().setObject(valueToSave, forKey: "preferenceName")

以后再找回来;

if let savedValue = NSUserDefaults.standardUserDefaults().stringForKey("preferenceName") {
    // Do something with savedValue
}

在Swift 3.0中

var valueToSave = "someValue"
UserDefaults.standard.set(valueToSave, forKey: "preferenceName")

if let savedValue = UserDefaults.standard.string(forKey: "preferenceName") {

}

谢谢,因为最初的问题是快速解答,所以+1
Akshansh Thakur

午饭后我的犬儒主义检测器出现问题。最初的问题是在2010年提出的。由于Swift是今天的发展之路,因此我对此表示反对。
罗伊·福克

12

像这样:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

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

然后检索:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

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

您应该真正查看Apple的NSUserDefaults类参考以及本教程:iPhone编程教程–使用NSUserDefaults保存/检索数据


12

不要忘记此语句,否则它可能并不总是有效:

[standardUserDefaults synchronize];

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

正在检索

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"];


5

好的做法还是对密钥使用常量,以避免在不使用同一密钥进行存储和读取的情况下出现的错误

NSString* const TIME_STAMPS_KEY = @"TIME_STAMPS_KEY";

1
-(void)saveToUserDefaults:(NSString*)string_to_store keys:(NSString *)key_for_the_String
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

    if (standardUserDefaults) {
        [standardUserDefaults setObject:string_to_store forKey:key_for_the_String];
        [standardUserDefaults synchronize];
    }
}

并通过以下方式调用:

[self saveToUserDefaults:@"string_to_store" : @"key_for_the_string"];

使用以下方法检索字符串:

NSString * stored_string = [[NSUserDefaults standardUserDefaults] stringforkey:key_for_the_String]

1

第一视

    {
    NSMutableArray *array; }
- (void)viewDidLoad {
    [super viewDidLoad];
    array = [[NSMutableArray alloc]init];
    array = [[NSUserDefaults  standardUserDefaults]objectForKey:@"userlist"];

     NSLog(@"%lu",(unsigned long)array.count);
    if (array>0)
    {
        for (int i=0; i<array.count; i++)
        {
            NSDictionary *dict1 = @{@"Username":[[array valueForKey:@"Username"] objectAtIndex:i],@"Mobilenumber":[[array valueForKey:@"Mobilenumber"] objectAtIndex:i],@"Firstname":[[array valueForKey:@"Firstname"] objectAtIndex:i],@"Lastname":[[array valueForKey:@"Lastname"] objectAtIndex:i],@"dob":[[array valueForKey:@"dob"] objectAtIndex:i],@"image":[[array valueForKey:@"image"] objectAtIndex:i]};
            NSLog(@"%@",dict1);
            NSArray *array1 = [[NSArray alloc]initWithObjects:dict1, nil];
            [[NSUserDefaults standardUserDefaults] setObject:array1 forKey:@"UserList"];
        }

    }
     }

图像选择器

     - (void)imagePickerController:(UIImagePickerController *)picker         didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    self.imaGe.image = chosenImage;

    [picker dismissViewControllerAnimated:YES completion:NULL];
     }
  • (IBAction)submitBton:(id)sender {

    NSMutableArray *array2 = [[NSMutableArray alloc]initWithArray: 
    [[NSUserDefaults standardUserDefaults]objectForKey:     
        @"userlist"]];                                
    
    UIImage *ima = _imaGe.image;
    NSData *imagedata = UIImageJPEGRepresentation(ima,100);
    
    NSDictionary *dict =  @{@"Username":_userTxt.text,@"Lastname":_lastTxt.text,@"Firstname":_firstTxt.text,@"Mobilenumber":_mobTxt.text,@"dob":_dobTxt.text,@"image":imagedata};
    
       [array2 addObject:dict];
      [[NSUserDefaults standardUserDefaults]setObject:array2    
      forKey:@"userlist"];
       NSLog(@"%@",array2);
    
      [self performSegueWithIdentifier:@"second" sender:self];
    
     }
    • (IBAction)chooseImg:{id)sender {

      UIImagePickerController * picker = [[UIImagePickerController
      alloc] init]; picker.delegate =自我; picker.allowsEditing = YES; picker.sourceType =
      UIImagePickerControllerSourceTypePhotoLibrary; [自身presentViewController:picker动画:是完成:NULL];

      }


第二个视图 {NSMutableArray * arr; }

- (void)viewDidLoad {
    [super viewDidLoad];

     arr =[[NSMutableArray alloc]init];
    arr = [[NSUserDefaults standardUserDefaults]objectForKey:@"userlist"]; }

#pragma mark- TableView DataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1; }

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return arr.count; }

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"tablecell";
    TableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellId];
    cell.userLbl.text =[[arr valueForKey:@"username"] objectAtIndex:indexPath.row];
    cell.ageLbl.text =[[arr valueForKey:@"dob"] objectAtIndex:indexPath.row];
    cell.profileImg.image =[UIImage imageNamed:[[arr valueForKey:@"image"] objectAtIndex:indexPath.row]];
    return cell; }

1

Swift5和Xcode 10.2中

//Save
UserDefaults.standard.set(true, forKey: "Key1") //Bool
UserDefaults.standard.set(1, forKey: "Key2")  //Integer
UserDefaults.standard.set("This is my string", forKey: "Key3") //String
UserDefaults.standard.synchronize()

//Retrive
UserDefaults.standard.bool(forKey: "Key1")
UserDefaults.standard.integer(forKey: "Key2")
UserDefaults.standard.string(forKey: "Key3")

//Remove
UserDefaults.standard.removeObject(forKey: "Key3")

注意:将文本数据(表示字符串,数组,字典等)保存在UserDefaults中。不要将图像保存在UserDefaults中,不建议(将图像保存在本地目录中)。


0

为了节省使用此:

[[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:@"KTerminated"];
[[NSUserDefaults standardUserDefaults]synchronize];

对于检索使用此:

[[[NSUserDefaults standardUserDefaults]stringForKey:@"KTerminated"] isEqualToString:@"YES"];

0

在这里,我为Swift创建了两个函数,该函数要求保存并从首选项中检索键的值

也许这对你有帮助

//用于保存对象

static func setObject(value:AnyObject ,key:String)
{
    let pref = NSUserDefaults.standardUserDefaults()
    pref.setObject(value, forKey: key)
    pref.synchronize()
}

static func getObject(key:String) -> AnyObject
{
    let pref = NSUserDefaults.standardUserDefaults()
    return pref.objectForKey(key)!
}

0

Swift 3更新

func setObject(value:AnyObject ,key:String)
{
    let pref = UserDefaults.standard
    pref.set(value, forKey: key)
    pref.synchronize()
}

func getObject(key:String) -> AnyObject
{
    let pref = UserDefaults.standard
    return pref.object(forKey: key)! as AnyObject
}

0

在Swift 4.0.3 Xcode 9中

============set  Data in UserDefaults =========

  UserDefaults.standard.set(userName, forKey: "userName")
  UserDefaults.standard.synchronize()

============Get Data in UserDefaults =========

  let userName = UserDefaults.standard.string(forKey: "userName")
  print(userName ?? "Gera")

  userNameTextField.text = ""+userName!
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.