如何保存字符串到NSUserDefaults?


当前回答

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

其他回答

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

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

[standardUserDefaults synchronize];
-(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]

FirstView

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

    }
     }

image picker

     - (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 = self; picker.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; }

对于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)!
}