在iPhone应用程序中保存数据的最简单方法是什么?

时间:2023-01-27 16:42:38

I want to persist a very simple string. For example "abc". What's the easiest way to do this? I don't want to use a SqlLite database.

我想坚持一个非常简单的字符串。例如“abc”。最简单的方法是什么?我不想使用SqlLite数据库。

2 个解决方案

#1


18  

If it is just one single string NSUserDefaults is probably the easiest way.

如果它只是一个单独的字符串NSUserDefaults可能是最简单的方法。

// write
[[NSUserDefaults standardUserDefaults] setObject:@"abc" forKey:@"MY_PERSISTENT_KEY"];

// read
NSString *abc = [[NSUserDefaults standardUserDefaults] valueForKey:@"MY_PERSISTENT_KEY"];

#2


0  

You can make your objects conform to NSCoding, then write them to a file using an NSKeyedArchiver.

您可以使对象符合NSCoding,然后使用NSKeyedArchiver将它们写入文件。

NSString* path = [self pathForDataFile];
NSMutableDictionary* rootObject = [NSMutableDictionary dictionary];
[rootObject setValue: someObject forKey: @"SomeObject"];

// Commit data to file
[NSKeyedArchiver archiveRootObject: rootObject toFile: path];

#1


18  

If it is just one single string NSUserDefaults is probably the easiest way.

如果它只是一个单独的字符串NSUserDefaults可能是最简单的方法。

// write
[[NSUserDefaults standardUserDefaults] setObject:@"abc" forKey:@"MY_PERSISTENT_KEY"];

// read
NSString *abc = [[NSUserDefaults standardUserDefaults] valueForKey:@"MY_PERSISTENT_KEY"];

#2


0  

You can make your objects conform to NSCoding, then write them to a file using an NSKeyedArchiver.

您可以使对象符合NSCoding,然后使用NSKeyedArchiver将它们写入文件。

NSString* path = [self pathForDataFile];
NSMutableDictionary* rootObject = [NSMutableDictionary dictionary];
[rootObject setValue: someObject forKey: @"SomeObject"];

// Commit data to file
[NSKeyedArchiver archiveRootObject: rootObject toFile: path];