iOSが開発したデータストレージ
4358 ワード
一、データストレージのいくつかの方式
1.NSUserDefaults
// 1.
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:@"1", nil];
// 2. NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:arr forKey:@"ArrKey"];
// 3.
[[NSUserDefaults standardUserDefaults] synchronize];
// 4. NSUserDefaults
NSArray *arr = [[NSUserDefaults standardUserDefaults] objectForKey:@"ArrKey"];
2.Plistファイル-Property List(Xcodeのリソースパッケージであり、同じストレージツール)
1:
// 1. Property List
// 2.
// 3.
NSString *str = [[NSBundle mainBundle] pathForResource:@"testPlistFile" ofType:@"plist"];
// 4.
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:str];
2:
// 1.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// 2.
NSString *plistPath = [paths objectAtIndex:0];
// 3. Plist
NSString *fileName = [plistPath stringByAppendingPathComponent:@"testPlist.plist"];
// 4. Plist
NSFileManager *fm = [NSFileManager defaultManager];
[fm createFileAtPath:fileName contents:nil attributes:nil];
// 5.
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"test", nil];
// 6. Plist
[dict writeToFile:fileName atomically:YES];
// 7. Plist
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:fileName];
3.アーカイブ解除
// 1. XHModel, NSCoding
#import
@interface XHModel:NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
#import "XHModel.h"
@implementation XHModel
- (id)initWithCode:(NSCode *)aDecoder
{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [[aDecoder decodeObjectForKey:@"age"] integerValue];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:[NSNumber numberWithInteger:self.age] forKey:@"age"];
}
- (NSString *)description
{
return [NSString stringWithFormat:@"%@--%ld ", self.name, (long)self.age];
}
// 2.
XHModel *model = [[XHModel alloc] init];
model.name = @" ";
model.age = 18;
// 3. NSData
NSMutableData *data = [[NSMutableData alloc] init];
// 4.
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// 5.
[archiver encodeObject:model forKey:@"model"];
[archiver finishEncoding];
// 6.
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [array.firstObject stringByAppendingPathComponent:@"archiverModel"];
if([data writeToFile:fileName atomically:YES]){
NSLog(@" ");
}
//
NSData *undata = [[NSData alloc] initWithContentsOfFile:fileName];
//
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:undata];
// model
TestModel *unModel = [unarchiver decodeObjectForKey:@"model"];
NSLog(@"%@",unModel);
//
[unarchiver finishDecoding];
4.砂入れ
######5.NSUserDefaults
######6.NSUserDefaults