238

如何将字符串保存到NSUserDefaults?

4

16 回答 16

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

稍后取回

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"preferenceName"];
于 2010-06-19T05:37:30.050 回答
51

更确切地说

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

    if (standardUserDefaults) {
        [standardUserDefaults setObject:myString forKey:@"timestamps"];
        [standardUserDefaults synchronize];
    }
}
于 2010-06-19T05:38:06.693 回答
34

以下是使用 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") {

}
于 2015-04-25T15:48:08.120 回答
13

像这样的东西:

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 保存/检索数据

于 2010-06-19T06:04:31.137 回答
13

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

[standardUserDefaults synchronize];
于 2013-03-05T10:48:00.153 回答
8
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"];
于 2015-02-26T09:38:14.107 回答
7

[[NSUserDefaults standardUserDefaults] setValue:aString forKey:aKey]

于 2010-06-19T05:37:36.240 回答
6

一个好的做法是使用一个常量作为键来避免你不使用相同的键存储和读取的错误

NSString* const TIME_STAMPS_KEY = @"TIME_STAMPS_KEY";
于 2013-08-12T11:28:59.517 回答
4

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 中,不推荐(将图像保存在本地目录中)。

于 2018-10-12T10:53:23.810 回答
2
-(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]
于 2015-06-23T12:55:42.777 回答
2

第一视图

    {
    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]; 选择器.delegate = self; 选择器.allowsEditing = YES;picker.sourceType =
      UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController:picker animated:YES completion: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; }
于 2017-01-09T07:20:53.980 回答
1

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
}
于 2017-03-26T17:21:33.363 回答
1

在这里,对于 Swift,我创建了两个函数,它们从 Preference 中调用键的保存和检索值

可能这对你很有帮助

// 用于保存对象

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)!
}
于 2016-09-20T12:56:49.027 回答
1

为了节省使用这个:

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

对于检索使用这个:

[[[NSUserDefaults standardUserDefaults]stringForKey:@"KTerminated"] isEqualToString:@"YES"];
于 2016-01-07T08:03:12.397 回答
1

在 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!
于 2018-01-09T07:31:38.807 回答
1

斯威夫特在这里更新:

let userID = "BOB"  

声明用户默认值:

let defaults = UserDefaults.standard
defaults.setValue(userID, forKey: "userID")

得到它:

let userID = defaults.object(forKey: "userID")
于 2021-02-04T22:40:27.163 回答