简体   繁体   中英

Shared Preferences in Objective C from Android

Is there anyway to re-create this code into Objective c? I am just starting out, and I need some help.

String name = #;// Will often vary.

SharedPreferences userData = this.getSharedPreferences(name + "userdata", MODE_PRIVATE);
    Editor edit = userData.edit();
    edit.clear();
    edit.putFloat("rating", Rating.getRating());
    edit.putString("good", txtGood.getText().toString().trim());
    edit.putString("improve", txtImprove.getText().toString().trim());
    edit.commit();
    Log.d(TAG, "Saving Data");

The advantage of this code is that is makes a new SharedPreference everytime the method is called. With my experience using NSUserDefaults, it was only able to make 1 batch of data.

NSUserDefaults (Objective-C) are similar to SharedPreferences (Android).

   // To save data
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"title" forKey:@"kTitle"];
    [defaults setInteger:21 forKey:@"kSrNo"];
    [defaults synchronize];
    NSLog(@"Data are saved to defaults.");

   // To retrive it back
    NSString *title = [defaults objectForKey:@"kTitle"];
    int srno = [defaults integerForKey:@"kSrNo"];
    NSLog(@"Data from defaults--> Title: %@ SrNO: %d",title,srno);
- (NSString*)GetFilePath:(NSString*)filename
{
     NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
    NSString *documentsDirectory = [paths objectAtIndex:0]; //2
    NSString* file = [[NSString alloc]initWithFormat:@"%@.plist",filename];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:file];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath: path]) //4
    {
        NSString *bundle = [[NSBundle mainBundle] pathForResource:filename ofType:@"plist"]; //5

        [fileManager copyItemAtPath:bundle toPath:path error:&error]; //6
    }  
    return path;
}

and call like this from any method:

NSMutableDictionary* TempDict = [[NSMutableDictionary alloc]initWithContentsOfFile:[self GetFilePath:@"FileName"]];

Plist is like sharedpreferences where you can save anykind of data. arrays,strings,booleans etc and also there is no limit to that. you can take look at this for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM