Toa*_*tor 47 iphone objective-c ios
问题标题几乎让它消失了 - 我希望我的应用程序记住一些事情.它是某种计算器,因此它应该保存最后使用的值和一些用户可选择的设置.
基本上我想保存一些浮动和BOOL并在下次加载应用程序时再次加载它们.
什么是最好最简单的方法?
谢谢!!
Gau*_*ses 131
最简单的方法之一是将其保存在NSUserDefaults
:
设置:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:value
forKey:key];
// – setBool:forKey:
// – setFloat:forKey:
// in your case
[userDefaults synchronize];
Run Code Online (Sandbox Code Playgroud)
获得:
[[NSUserDefaults standardUserDefaults] objectForKey:key];
– boolForKey:
Run Code Online (Sandbox Code Playgroud)
和
– floatForKey:
在你的情况下.
除了非常好的NSUserDefaults方法之外,还有另一种简单的方法可以将NSArray,NSDictionary或NSData中的数据存储在一个文件中.您也可以使用这些方法:
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
Run Code Online (Sandbox Code Playgroud)
分别(对于NSDictionary):
+ (id)dictionaryWithContentsOfFile:(NSString *)path
Run Code Online (Sandbox Code Playgroud)
你只需要提供一个有效的路径到一个位置.根据iOS应用程序编程指南,/ Library/Caches目录是存储应用程序启动之间需要保留的数据的最佳位置.(见这里)
为了在您的文档directoy中存储/加载名为"managers"的字段中的字典,您可以使用以下方法:
-(void) loadDictionary {
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
//create a destination file name to write the data :
NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", cacheDirectory];
NSDictionary* panelLibraryContent = [NSDictionary dictionaryWithContentsOfFile:fullFileName];
if (panelLibraryContent != nil) {
// load was successful do something with the data...
} else {
// error while loading the file
}
}
-(void) storeDictionary:(NSDictionary*) dictionaryToStore {
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the
//cache directory:
NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", cacheDirectory];
if (dictionaryToStore != nil) {
[dictionaryToStore writeToFile:fullFileName atomically:YES];
}
}
Run Code Online (Sandbox Code Playgroud)
无论如何,这种方法非常有限,如果你想存储更复杂的数据,你必须花费大量的额外工作.在这种情况下,CoreData API非常方便.
设置
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(value, forKey: key)
// userDefaults.setFloat(12.34, forKey: "myFloatKey")
// userDefaults.setBool(true, forKey: "myBoolKey")
Run Code Online (Sandbox Code Playgroud)
需要注意的是为iOS 8及更高版本,通话userDefaults.synchronize()
是不推荐使用.
入门
let userDefaults = NSUserDefaults.standardUserDefaults()
if let value = userDefaults.objectForKey(key) {
print(value)
}
Run Code Online (Sandbox Code Playgroud)
请注意,userDefaults.boolForKey
并userDefaults.floatForKey
都返回非可选值,所以他们永远不会nil
(仅false
或0.0
).
归档时间: |
|
查看次数: |
38059 次 |
最近记录: |