我的应用开发与调查问题有关。 (有趣的,而不是无聊的!)我想为每个相对于用户的问题创建一个层级系统,每次他们回答一个特定的问题,我想将一个值与该用户的问题相关联,确定他们的问题的次数我回答了。
我相信我需要实现此目标的方式是NSMutableDictionary
和NSUserDefaults
。这是我的代码的简化版本:
NSMutableDictionary *questionTierDictionary = [[NSMutableDictionary alloc]init];
[[NSUserDefaults standardUserDefaults] objectForKey:@"questionTiers"];
[questionTierDictionary setObject:[NSNumber numberWithInt:4] forKey:@(2)];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"%@", questionTierDictionary);
此代码是否会无限期地将此数据保存到应用中,或者在用户关闭应用后它是否会消失?如果是这样,您对我如何轻松测试以查看数据是否已存储有任何建议吗?
答案 0 :(得分:1)
沙箱路径:
~~文件:
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString * docDir = [paths objectAtIndex:0];
~~~缓存:
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES); NSString * cachesDir = [paths objectAtIndex:0];
~~~ tmp:
NSString * tmpDir = NSTemporaryDirectory();
~~~ home sandbox:
NSString * homeDir = NSHomeDirectory();
~~~ for pic:
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]];
}
我希望我能帮到你!
答案 1 :(得分:0)
NSUserDefaults
将数据永久保存在您的应用程序目录中,直到您手动将其删除...以NSUserDefaults
代码保存对象
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"yourObject",@"yourKey", nil];
[[NSUserDefaults standardUserDefaults]setObject:dict forKey:@"dict"];
//fetch Like this
NSDictionary *dict1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"dict"];