写的都是我自己平时用的,有不足多多指教
1.归档
新建一个类 继承 NSObject 在.h文件中 声明你要存储的数据类型
@interface LodinModle : NSObject<NSCoding>//这个要添加
@property (nonatomic , copy) NSString *phong;
@property (nonatomic , copy) NSString *pass;
@property (nonatomic , copy) NSString *time;
.m文件中 实现协议(2个方法)
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.phong forKey:@"phong"];
[aCoder encodeObject:self.pass forKey:@"pass"];
[aCoder encodeObject:self.time forKey:@"time"];
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init ]) {
self.phong = [aDecoder decodeObjectForKey:@"phong"];
self.pass = [aDecoder decodeObjectForKey:@"pass"];
self.time = [aDecoder decodeObjectForKey:@"time"];
}
return self;
}
使用:
在需要保存数据的控制器中导入上面类的头文件
创建保存的数据
LodinModle *p = [[LodinModle alloc]init];
获取\创建保存的路径
NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];
[NSKeyedArchiver archiveRootObject:p toFile:path];
取出数据
获取路径 如上
p=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
2.偏好设置
保存数据
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject:要保存的数据 forKey:@"name"];
取出数据
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
NSString *hh_str = [defaults objectForKey:@"name"];
3.数据库(fmdb)
获取\创建路径
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName = [doc stringByAppendingPathComponent:@"S.sqlite"];
打开数据库
FMDatabase *db = [FMDatabase databaseWithPath:fileName];
[db open];
建表
[db executeUpdate:@"CREATE TABLE IF NOT EXISTS 表名 (数据名 类型, Age integer, Sex integer, Phone text, Address text, Photo blob)"];
插入数据
[db executeUpdate:@"INSERT INTO 表名(属性,属性) VALUES ('妮子',20)"];
修改数据
[db executeUpdate:@"UPDATE 表名 SET 属性 = '娃子狗' WHERE 属性 = 20;"];
筛选数据
[db executeUpdate:@"DELETE FROM 表名 WHERE 属性 < 22"];
遍历数据集
while ([rs next]) {
NSString *name = [rs stringForColumn:@"name"];
int age = [rs intForColumn:@"age"];
}
删除表
[db executeUpdate:@"DROP TABLE IF EXISTS 表名"];
关闭数据库
[db close]