将对象保存到应用程序,IOS

Saving objects to the app, IOS

我正在开发的应用程序与调查问题有关。 (有趣的,而不是无聊的!)我想为每个与用户相关的问题创建一个等级系统,每次他们回答一个特定的问题时,我想为该用户为该问题关联一个值,以确定他们的次数我已经回答了。

我认为实现此目标的方法是 NSMutableDictionaryNSUserDefaults。这是我的代码的简化版本:

NSMutableDictionary *questionTierDictionary = [[NSMutableDictionary alloc]init];

[[NSUserDefaults standardUserDefaults] objectForKey:@"questionTiers"];

[questionTierDictionary setObject:[NSNumber numberWithInt:4] forKey:@(2)];


[[NSUserDefaults standardUserDefaults] synchronize];

NSLog(@"%@", questionTierDictionary);

此代码会无限期地将此数据保存到应用程序中,还是会在用户关闭应用程序后消失?如果是这样,您对我如何轻松测试数据是否已存储有什么建议吗?

NSUserDefaults 将数据永久保存在您的应用程序目录中,直到您手动将其删除...以这样的 NSUserDefaults 代码保存对象

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"yourObject",@"yourKey", nil];

[[NSUserDefaults standardUserDefaults]setObject:dict forKey:@"dict"];

//fetch Like this

NSDictionary *dict1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"dict"];

沙盒路径:

~~ 文件:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docDir = [路径 objectAtIndex:0];

~~~ 缓存:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachesDir = [路径 objectAtIndex:0];

~~~ tmp:

NSString *tmpDir = NSTemporaryDirectory();

~~~ 主页沙箱:

NSString *homeDir = NSHomeDirectory();

~~~ 图片:

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"apple" ofType:@"png"];
UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];


示例:


NSFileManager* fm=[NSFileManager defaultManager];
if(![fm fileExistsAtPath:[self dataFilePath]]){
    //
    [fm createDirectoryAtPath:[self dataFilePath] withIntermediateDirectories:YES attributes:nil error:nil];

    //
    NSArray *files = [fm subpathsAtPath: [self dataFilePath] ];

    //
    NSData *data = [fm contentsAtPath:[self dataFilePath]];

    //
    NSData *data = [NSData dataWithContentOfPath:[self dataFilePath]];
}

希望能帮到你!