來自Android的Objective C中的共享首選項

[英]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.

反正有沒有重新創建這個代碼到Objective c?我剛剛開始,我需要一些幫助。

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.

這段代碼的優點是每次調用方法時都會創建一個新的SharedPreference。根據我使用NSUserDefaults的經驗,它只能生成1批數據。

2 个解决方案

#1


0  

- (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.

Plist就像共享首選項,您可以在其中保存任何數據。數組,字符串,布爾等,也沒有限制。你可以看看這個以獲取更多信息。

#2


4  

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

NSUserDefaults(Objective-C)類似於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);

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/07/24/7ad66c71ea9eeb158362fb56ace1b15.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com