【iOS】iOS数据存储,应用沙盒,XML,Preference,NSKeyedArchiver归档,SQLite3

版权声明:本文为博主原创,如需转载请注明出处。

应用沙盒

每个iOS应用都有自己的应用沙盒(应用沙盒就是文件系统目录),与其他文件系统隔离。应用必须待在自己的沙盒里,其他应用不能访问该沙盒

应用沙盒的文件系统目录,如下图所示(假设应用的名称叫Layer)

模拟器应用沙盒的根路径在: (apple是用户名, 6.0是模拟器版本)
/Users/apple/Library/Application Support/iPhone Simulator/6.0/Applications

在使用Xcode5的时候,模拟器中的app可以在电脑如下路径找到:

/Users/用户名/Library/Application Support/iPhone Simulator/系统版本号/Applications

而在Xcode6环境下,存放位置已经发生了变化。

调查发现,新的路径变成了/Users/{YOUR NAME}/Library/Developer/CoreSimulator/Devices/设备型号/data/Containers

其中设备型号是用uuid表示的,可以用如下命令获取它们之间的对应关系(stackoverflow):xcrun simctl list
再往下,app和本地文件已经分开放了:app在Bundle/Application下;本地文件在Data/Application下
每个目录下都是一堆uuid命名的文件夹,很难区分。

找的时候可以通过在app运行时打印bundle路径和NSHomeDirectory()发现具体路径。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
➜  Devices xcrun simctl list
== Device Types ==
iPhone 4s (com.apple.CoreSimulator.SimDeviceType.iPhone-4s)
iPhone 5 (com.apple.CoreSimulator.SimDeviceType.iPhone-5)
iPhone 5s (com.apple.CoreSimulator.SimDeviceType.iPhone-5s)
iPhone 6 (com.apple.CoreSimulator.SimDeviceType.iPhone-6)
iPhone 6 Plus (com.apple.CoreSimulator.SimDeviceType.iPhone-6-Plus)
iPhone 6s (com.apple.CoreSimulator.SimDeviceType.iPhone-6s)
iPhone 6s Plus (com.apple.CoreSimulator.SimDeviceType.iPhone-6s-Plus)
iPad 2 (com.apple.CoreSimulator.SimDeviceType.iPad-2)
iPad Retina (com.apple.CoreSimulator.SimDeviceType.iPad-Retina)
iPad Air (com.apple.CoreSimulator.SimDeviceType.iPad-Air)
iPad Air 2 (com.apple.CoreSimulator.SimDeviceType.iPad-Air-2)
iPad Pro (com.apple.CoreSimulator.SimDeviceType.iPad-Pro)
Apple TV 1080p (com.apple.CoreSimulator.SimDeviceType.Apple-TV-1080p)
Apple Watch - 38mm (com.apple.CoreSimulator.SimDeviceType.Apple-Watch-38mm)
Apple Watch - 42mm (com.apple.CoreSimulator.SimDeviceType.Apple-Watch-42mm)
== Runtimes ==
iOS 9.0 (9.0 - 13A344) (com.apple.CoreSimulator.SimRuntime.iOS-9-0)
iOS 9.1 (9.1 - 13B143) (com.apple.CoreSimulator.SimRuntime.iOS-9-1)
iOS 9.2 (9.2 - 13C75) (com.apple.CoreSimulator.SimRuntime.iOS-9-2)
iOS 9.3 (9.3 - 13E230) (com.apple.CoreSimulator.SimRuntime.iOS-9-3)
tvOS 9.2 (9.2 - 13Y227) (com.apple.CoreSimulator.SimRuntime.tvOS-9-2)
watchOS 2.2 (2.2 - 13V143) (com.apple.CoreSimulator.SimRuntime.watchOS-2-2)
== Devices ==
-- iOS 9.0 --
iPhone 4s (41931634-624C-4AB8-8652-9EFA6E816379) (Shutdown)
iPhone 5 (3A03D3D9-35BC-4AFC-8D3A-AA729DFA4417) (Shutdown)
iPhone 5s (9091604E-CB39-4089-B594-336212024A21) (Shutdown)
iPhone 6 (CB81F1ED-3B3F-407A-BF58-E5E932D253E2) (Shutdown)
iPhone 6 Plus (F166EB11-39BB-4EFA-87E3-0ADD79849409) (Shutdown)
iPhone 6s (F6487BC7-400C-4A91-A950-2A18B9558DC3) (Shutdown)
iPhone 6s Plus (1E17B5B9-9765-4306-A646-3253620178AE) (Shutdown)
iPad 2 (5C4751E6-1CA2-418C-891F-3C450C91DCE7) (Shutdown)
iPad Retina (14F984F6-3E7E-4BB3-A6F8-3EF337058DCF) (Shutdown)
iPad Air (C492DDAF-7CE3-45D3-9734-9EB221DF8EC3) (Shutdown)
iPad Air 2 (4136305D-8F47-4CD4-BED3-B274162E4223) (Shutdown)
-- iOS 9.1 --
iPhone 4s (20F804F4-3551-4975-8FAD-99B387FA7101) (Shutdown)
iPhone 5 (DF220FF8-4AD7-486D-9701-3DC532BF3190) (Shutdown)
iPhone 5s (89EC0AF7-2799-47C5-8CA6-26D978153FAE) (Shutdown)
iPhone 6 (873A48E8-DF55-46AA-9895-D723BFD65262) (Shutdown)
iPhone 6 Plus (2AC4B279-5B83-4EB3-BB6F-511FFBE8602E) (Shutdown)
iPhone 6s (86F1DE4C-B407-457C-B170-82FEE1FBA1DD) (Shutdown)
iPhone 6s Plus (AFA83ACE-0FE5-4814-81EB-189100A2D8B3) (Shutdown)
iPad 2 (33CE0EA4-F9AF-43FA-A5AE-8784ABB6DBB8) (Shutdown)
iPad Retina (EFA3EEE6-DBBB-424C-A1EB-988FE40C6E01) (Shutdown)
iPad Air (05398825-A9A4-41F2-8E91-DD1651E27C4C) (Shutdown)
iPad Air 2 (2F805563-E2E5-4708-A846-CBFB8F23BB98) (Shutdown)
iPad Pro (D2A724F2-BDEB-4D2E-AF83-3CD1A2DF929A) (Shutdown)
-- iOS 9.2 --
iPhone 4s (FFB2BDB2-B759-4F40-A396-A38A43D946E5) (Shutdown)
iPhone 5 (A60C4213-F011-4DBA-8E94-CCD8214E7B04) (Shutdown)
iPhone 5s (6A6F57A5-1057-4187-B034-AB085349DF6B) (Shutdown)
iPhone 6 (F9B18CA1-0D31-4077-9F4B-B94C195E0E67) (Shutdown)
iPhone 6 Plus (B9D38A37-C004-485B-83A9-C442AA92D644) (Shutdown)
iPhone 6s (9F8EB146-B2A2-4F1F-84CC-32D33E0A7187) (Shutdown)
iPhone 6s Plus (E09E8DE5-F60C-4F30-9144-B45A7DF9ED98) (Shutdown)
iPad 2 (92EE4298-E5FD-4408-93EF-554AF18EE12D) (Shutdown)
iPad Retina (B1DD1D12-F67A-4EC4-9833-1B6989BB8A45) (Shutdown)
iPad Air (3F1980FD-3C5B-43CF-834C-B4869B9A89C8) (Shutdown)
iPad Air 2 (42802305-9282-4A19-9B3B-5EBA3163B6EF) (Shutdown)
iPad Pro (02A937DA-694D-40DE-B1EE-604D8F46AD8F) (Shutdown)
-- iOS 9.3 --
iPhone 4s (BDE69A93-B858-4B5A-AB3F-CAD796FCC045) (Shutdown)
iPhone 5 (A95F5000-7E2A-455E-B847-9212722A4136) (Shutdown)
iPhone 5s (E5D555C0-C723-4338-BFCF-B5E2E669FE54) (Shutdown)
iPhone 6 (9226B68B-5702-4953-947B-0E655FADDE12) (Shutdown)
iPhone 6 Plus (C4E60731-2679-4237-8E24-AC9512DF9E9E) (Shutdown)
iPhone 6s (6F7F28DE-CE2A-40DE-B91B-203EA774B275) (Booted)
iPhone 6s Plus (115B2F18-065F-490B-9EAB-9C63B0BDE1CF) (Shutdown)
iPad 2 (EF2F1963-B398-45E8-A609-170F0F09E6AA) (Shutdown)
iPad Retina (0F830533-9A66-46EE-B0F8-388E12E41FCF) (Shutdown)
iPad Air (04ED9886-705E-4E63-9322-6EF1E04D2578) (Shutdown)
iPad Air 2 (816C1B6D-6F7F-4A41-A952-A84BFECE6230) (Shutdown)
iPad Pro (ECD0C28F-28CE-4CAB-A7C3-F31F7D4A3146) (Shutdown)
-- tvOS 9.2 --
Apple TV 1080p (8129655F-4134-4998-A2C9-0461C28FDF00) (Shutdown)
-- watchOS 2.2 --
Apple Watch - 42mm (2B69FD3C-1DBC-41AC-82BA-B8A4215E09C4) (Shutdown)
-- Unavailable: com.apple.CoreSimulator.SimRuntime.iOS-10-0 --
iPhone 5 (DF66161D-F762-44FB-BF8B-EE8FDECFD203) (Shutdown) (unavailable, runtime profile not found)
iPhone 5s (00F328A8-5704-4C88-A128-5D310C51B476) (Shutdown) (unavailable, runtime profile not found)
iPhone 6 (A83359F2-41E9-4FDB-971A-1022811451BE) (Shutdown) (unavailable, runtime profile not found)
iPhone 6 Plus (A824AD89-D1CE-4E04-AD73-0E0C333238C2) (Shutdown) (unavailable, runtime profile not found)
iPhone 6s (14B59EAE-E267-4CF9-90CF-65F1153E8B51) (Shutdown) (unavailable, runtime profile not found)
iPhone 6s Plus (CC3124B7-500A-470D-B5DB-F330F5B173E1) (Shutdown) (unavailable, runtime profile not found)
iPad Retina (2550E4C9-54B2-4AC1-BD64-8C21595B2FFA) (Shutdown) (unavailable, runtime profile not found)
iPad Air (B8CD31CA-1690-4F7E-BABA-087AC4C1E894) (Shutdown) (unavailable, runtime profile not found)
iPad Air 2 (7F6E412B-CC71-4E92-A542-10AB7CEE0440) (Shutdown) (unavailable, runtime profile not found)
iPad Pro (12.9 inch) (693C487D-BBDC-4ED6-A0B5-43832111CA89) (Shutdown) (unavailable, runtime profile not found)
iPad Pro (9.7 inch) (580B7423-99CD-411A-AD11-8C7906C44279) (Shutdown) (unavailable, runtime profile not found)
iPhone SE (7482B157-12B7-4713-9BF7-F4C7083EC1B5) (Shutdown) (unavailable, runtime profile not found)
-- Unavailable: com.apple.CoreSimulator.SimRuntime.tvOS-10-0 --
Apple TV 1080p (F9A62967-74C3-49DE-8A35-979531501889) (Shutdown) (unavailable, runtime profile not found)
-- Unavailable: com.apple.CoreSimulator.SimRuntime.watchOS-3-0 --
Apple Watch - 38mm (CFD06DDD-5ED7-4C2E-AD2D-180959274F4E) (Shutdown) (unavailable, runtime profile not found)
Apple Watch - 42mm (835B5691-599C-4A5E-919F-04F68991042F) (Shutdown) (unavailable, runtime profile not found)
== Device Pairs ==
B136137E-9B10-4427-9706-59FBD01359E1 (active, disconnected)
Watch: Apple Watch - 42mm (2B69FD3C-1DBC-41AC-82BA-B8A4215E09C4) (Shutdown)
Phone: iPhone 6s Plus (115B2F18-065F-490B-9EAB-9C63B0BDE1CF) (Shutdown)
07105DA6-F4F3-4FF4-8945-4A1E0A1B97AE (unavailable)
Watch: Apple Watch - 38mm (CFD06DDD-5ED7-4C2E-AD2D-180959274F4E) (Shutdown)
Phone: iPhone 6 (A83359F2-41E9-4FDB-971A-1022811451BE) (Shutdown)
E142260B-6DF1-4B45-8389-E108F0F79652 (unavailable)
Watch: Apple Watch - 42mm (835B5691-599C-4A5E-919F-04F68991042F) (Shutdown)
Phone: iPhone 6 Plus (A824AD89-D1CE-4E04-AD73-0E0C333238C2) (Shutdown)

应用沙盒结构分析

  • 应用程序包:(上图中的Layer)包含了所有的资源文件和可执行文件
  • Documents:保存应用运行时生成的需要持久化的数据,iTunes同步设备时会备份该目录。例如,游戏应用可将游戏存档保存在该目录
  • tmp:保存应用运行时所需的临时数据,使用完毕后再将相应的文件从该目录删除。应用没有运行时,系统也可能会清除该目录下的文件。iTunes同步设备时不会备份该目录
  • Library/Caches:保存应用运行时生成的需要持久化的数据,iTunes同步设备时不会备份该目录。一般存储体积大、不需要备份的非重要数据
  • Library/Preference:保存应用的所有偏好设置,iOS的Settings(设置)应用会在该目录中查找应用的设置信息。iTunes同步设备时会备份该目录

应用沙盒目录的常见获取方式

  • 沙盒根目录
1
NSString *home = NSHomeDirectory();
  • Documents:(2种方式)

  • 利用沙盒根目录拼接”Documents”字符串

1
2
3
NSString *home = NSHomeDirectory();
NSString *documents = [home stringByAppendingPathComponent:@"Documents"];
// 不建议采用,因为新版本的操作系统可能会修改目录名
  • 利用NSSearchPathForDirectoriesInDomains函数
1
2
3
4
5
// NSUserDomainMask 代表从用户文件夹下找
// YES 代表展开路径中的波浪字符“~”
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO);
// 在iOS中,只有一个目录跟传入的参数匹配,所以这个集合里面只有一个元素
NSString *documents = [array objectAtIndex:0];

tem 目录

1
NSString *tmp = NSTemporaryDirectory();

Library/Caches:(跟Documents类似的2种方法)

  • 利用沙盒根目录拼接”Caches”字符串
  • 利用NSSearchPathForDirectoriesInDomains函数(将函数的第2个参数改为:NSCachesDirectory即可)

Library/Preference:通过NSUserDefaults类存取该目录下的设置信息

属性列表

  • 属性列表是一种XML格式的文件,拓展名为plist
  • 如果对象是NSString、NSDictionary、NSArray、NSData、NSNumber等类型,就可以使用writeToFile:atomically:方法直接将对象写到属性列表文件中

属性列表-归档NSDictionary

将一个NSDictionary对象归档到一个plist属性列表中

1
2
3
4
5
6
7
// 将数据封装成字典
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"小明" forKey:@"name"];
[dict setObject:@"15013141314" forKey:@"phone"];
[dict setObject:@"27" forKey:@"age"];
// 将字典持久化到Documents/stu.plist文件中
[dict writeToFile:path atomically:YES];

写入结果

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>age</key>
<string>27</string>
<key>name</key>
<string>小明</string>
<key>phone</key>
<string>15013141314</string>
</dict>
</plist>

读取属性列表,恢复NSDictionary对象

读取属性列表,恢复NSDictionary对象

1
2
3
4
5
// 读取Documents/stu.plist的内容,实例化NSDictionary
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(@"name:%@", [dict objectForKey:@"name"]);
NSLog(@"phone:%@", [dict objectForKey:@"phone"]);
NSLog(@"age:%@", [dict objectForKey:@"age"]);

打印结果:

1
2
3
2016-08-24 09:47:42.626 PersonalContacts02[2225:169033] name:小明
2016-08-24 09:47:42.626 PersonalContacts02[2225:169033] phone:15013141314
2016-08-24 09:47:42.626 PersonalContacts02[2225:169033] age:27

属性列表-NSDictionary的存储和读取过程

偏好设置

  • 很多iOS应用都支持偏好设置,比如保存用户名、密码、字体大小等设置,iOS提供了一套标准的解决方案来为应用加入偏好设置功能
  • 每个应用都有个NSUserDefaults实例,通过它来存取偏好设置
  • 比如,保存用户名、字体大小、是否自动登录
1
2
3
4
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"yoferzhang" forKey:@"username"];
[defaults setFloat:18.0f forKey:@"text_size"];
[defaults setBool:YES forKey:@"auto_login"];

读取上次保存的设置

1
2
3
4
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *username = [defaults stringForKey:@"username"];
float textSize = [defaults floatForKey:@"text_size"];
BOOL autoLogin = [defaults boolForKey:@"auto_login"];

注意:UserDefaults设置数据时,不是立即写入,而是根据时间戳定时地把缓存中的数据写入本地磁盘。所以调用了set方法之后数据有可能还没有写入磁盘应用程序就终止了。出现以上问题,可以通过调用synchornize方法强制写入

1
[defaults synchornize];

NSKeyedArchiver

如果对象是NSString、NSDictionary、NSArray、NSData、NSNumber等类型,可以直接用NSKeyedArchiver进行归档和恢复

不是所有的对象都可以直接用这种方法进行归档,只有遵守了NSCoding协议的对象才可以
NSCoding协议有2个方法:

  • encodeWithCoder:

每次归档对象时,都会调用这个方法。一般在这个方法里面指定如何归档对象中的每个实例变量,可以使用encodeObject:forKey:方法归档实例变量

  • initWithCoder:

每次从文件中恢复(解码)对象时,都会调用这个方法。一般在这个方法里面指定如何解码文件中的数据为对象的实例变量,可以使用decodeObject:forKey方法解码实例变量

NSKeyedArchiver-归档NSArray

归档一个NSArray对象到Documents/array.archive

1
2
NSArray *array = [NSArray arrayWithObjects:@"a",@"b",nil];
[NSKeyedArchiver archiveRootObject:array toFile:path];

恢复(解码)NSArray对象

1
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

NSKeyedArchiver-归档Person对象(Person.h)

Person对象(Person.h)

1
2
3
4
5
@interface Person : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) float height;
@end

Person对象(Person.m)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@implementation Person

- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.name forKey:@"name"];
[encoder encodeInt:self.age forKey:@"age"];
[encoder encodeFloat:self.height forKey:@"height"];
}

- (id)initWithCoder:(NSCoder *)decoder {
self.name = [decoder decodeObjectForKey:@"name"];
self.age = [decoder decodeIntForKey:@"age"];
self.height = [decoder decodeFloatForKey:@"height"];
return self;
}

@end

归档Person对象(编码和解码)

  • 归档(编码)
1
2
3
4
5
6
7
8
NSArray *array =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [array objectAtIndex:0];
NSString *filePath = [documents stringByAppendingPathComponent:@"data.plist"];
Person *person = [[Person alloc] init];
person.name = @"yoferzhang";
person.age = 27;
person.height = 1.83f;
[NSKeyedArchiver archiveRootObject:person toFile:filePath];

data.plist

  • 恢复(解码)
1
Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

归档对象的注意

如果父类也遵守了NSCoding协议,请注意:

应该在encodeWithCoder:方法中加上一句

1
[super encodeWithCode:encode];

确保继承的实例变量也能被编码,即也能被归档

应该在initWithCoder:方法中加上一句

1
self = [super initWithCoder:decoder];

确保继承的实例变量也能被解码,即也能被恢复

NSData

  • 使用archiveRootObject:toFile:方法可以将一个对象直接写入到一个文件中,但有时候可能想将多个对象写入到同一个文件中,那么就要使用NSData来进行归档对象
  • NSData可以为一些数据提供临时存储空间,以便随后写入文件,或者存放从磁盘读取的文件内容。可以使用[NSMutableData data]创建可变数据空间

NSData-归档2个Person对象到同一文件中

  • 归档(编码)
1
2
3
4
5
6
7
8
9
10
11
// 新建一块可变数据区
NSMutableData *data = [NSMutableData data];
// 将数据区连接到一个NSKeyedArchiver对象
NSKeyedArchiver *archiver = [[[NSKeyedArchiver alloc] initForWritingWithMutableData:data] autorelease];
// 开始存档对象,存档的数据都会存储到NSMutableData中
[archiver encodeObject:person1 forKey:@"person1"];
[archiver encodeObject:person2 forKey:@"person2"];
// 存档完毕(一定要调用这个方法)
[archiver finishEncoding];
// 将存档的数据写入文件
[data writeToFile:path atomically:YES];
  • 恢复(解码)
1
2
3
4
5
6
7
8
// 从文件中读取数据
NSData *data = [NSData dataWithContentsOfFile:path];
// 根据数据,解析成一个NSKeyedUnarchiver对象
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
Person *person1 = [unarchiver decodeObjectForKey:@"person1"];
Person *person2 = [unarchiver decodeObjectForKey:@"person2"];
// 恢复完毕
[unarchiver finishDecoding];

利用归档实现深复制

比如对一个Person对象进行深复制

1
2
3
4
5
6
7
// 临时存储person1的数据
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:person1];
// 解析data,生成一个新的Person对象
Student *person2 = [NSKeyedUnarchiver unarchiveObjectWithData:data];
// 分别打印内存地址
NSLog(@"person1:0x%x", person1); // person1:0x7177a60
NSLog(@"person2:0x%x", person2); // person2:0x7177cf0

SQLite3

  • SQLite3是一款开源的嵌入式关系型数据库,可移植性好、易使用、内存开销小
  • SQLite3是无类型的,意味着你可以保存任何类型的数据到任意表的任意字段中。比如下列的创表语句是合法的:
1
2
3
create table t_person(name, age);
为了保证可读性,建议还是把字段类型加上:
create table t_person(name text, age integer);
  • SQLite3常用的5种数据类型:text、integer、float、boolean、blob
  • 在iOS中使用SQLite3,首先要添加库文件libsqlite3.dylib和导入主头文件

创建、打开、关闭数据库

  • 创建或打开数据库
1
2
3
// path为:~/Documents/person.db
sqlite3 *db;
int result = sqlite3_open([path UTF8String], &db);

代码解析:

  • sqlite3_open()将根据文件路径打开数据库,如果不存在,则会创建一个新的数据库。如果result等于常量SQLITE_OK,则表示成功打开数据库
  • sqlite3 *db:一个打开的数据库实例
  • 数据库文件的路径必须以C字符串(而非NSString)传入

关闭数据库:

1
sqlite3_close(db);

执行不返回数据的SQL语句

执行创表语句

1
2
3
char *errorMsg;  // 用来存储错误信息
char *sql = "create table if not exists t_person(id integer primary key autoincrement, name text, age integer);";
int result = sqlite3_exec(db, sql, NULL, NULL, &errorMsg);

代码解析:

  • sqlite3_exec()可以执行任何SQL语句,比如创表、更新、插入和删除操作。但是一般不用它执行查询语句,因为它不会返回查询到的数据
  • sqlite3_exec()还可以执行的语句:
  1. 开启事务:begin transaction;
  2. 回滚事务:rollback;
  3. 提交事务:commit;

带占位符插入数据

1
2
3
4
5
6
7
8
9
10
char *sql = "insert into t_person(name, age) values(?, ?);";
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
sqlite3_bind_text(stmt, 1, "母鸡", -1, NULL);
sqlite3_bind_int(stmt, 2, 27);
}
if (sqlite3_step(stmt) != SQLITE_DONE) {
NSLog(@"插入数据错误");
}
sqlite3_finalize(stmt);

sqlite3_prepare_v2()返回值等于SQLITE_OK,说明SQL语句已经准备成功,没有语法问题

sqlite3_bind_text():大部分绑定函数都只有3个参数

  1. 第1个参数是sqlite3_stmt *类型
  2. 第2个参数指占位符的位置,第一个占位符的位置是1,不是0
  3. 第3个参数指占位符要绑定的值
  4. 第4个参数指在第3个参数中所传递数据的长度,对于C字符串,可以传递-1代替字符串的长度
  5. 第5个参数是一个可选的函数回调,一般用于在语句执行后完成内存清理工作

sqlite_step():执行SQL语句,返回SQLITE_DONE代表成功执行完毕

sqlite_finalize():销毁sqlite3_stmt *对象

查询数据

1
2
3
4
5
6
7
8
9
10
11
12
char *sql = "select id,name,age from t_person;";
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
int _id = sqlite3_column_int(stmt, 0);
char *_name = (char *)sqlite3_column_text(stmt, 1);
NSString *name = [NSString stringWithUTF8String:_name];
int _age = sqlite3_column_int(stmt, 2);
NSLog(@"id=%i, name=%@, age=%i", _id, name, _age);
}
}
sqlite3_finalize(stmt)

sqlite3_step()返回SQLITE_ROW代表遍历到一条新记录

sqlite3_column_*()用于获取每个字段对应的值,第2个参数是字段的索引,从0开始

新博客文章地址:【iOS】iOS数据存储,应用沙盒,XML,Preference,NSKeyedArchiver归档,SQLite3
CSDN文章地址:【iOS】iOS数据存储,应用沙盒,XML,Preference,NSKeyedArchiver归档,SQLite3

文章目录
  1. 1. 应用沙盒
    1. 1.1. 应用沙盒结构分析
    2. 1.2. 应用沙盒目录的常见获取方式
  2. 2. 属性列表
    1. 2.1. 属性列表-归档NSDictionary
    2. 2.2. 读取属性列表,恢复NSDictionary对象
    3. 2.3. 属性列表-NSDictionary的存储和读取过程
  3. 3. 偏好设置
  4. 4. NSKeyedArchiver
    1. 4.1. NSKeyedArchiver-归档NSArray
    2. 4.2. NSKeyedArchiver-归档Person对象(Person.h)
    3. 4.3. 归档对象的注意
    4. 4.4. NSData
    5. 4.5. NSData-归档2个Person对象到同一文件中
    6. 4.6. 利用归档实现深复制
  5. 5. SQLite3
    1. 5.1. 创建、打开、关闭数据库
    2. 5.2. 执行不返回数据的SQL语句
    3. 5.3. 带占位符插入数据
    4. 5.4. 查询数据