1

无论如何要将此代码重新创建到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");

此代码的优点是每次调用该方法时都会创建一个新的 SharedPreference。根据我使用 NSUserDefaults 的经验,它只能生成 1 批数据。

4

2 回答 2

5

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);
于 2013-07-24T04:01:36.193 回答
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;
}

并从任何方法这样调用:

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

Plist 就像 sharedpreferences 一样,您可以在其中保存任何类型的数据。数组、字符串、布尔值等,也没有限制。你可以看看这个以获取更多信息。

于 2013-07-24T04:42:53.420 回答