iOS - 文件与数据(File & Data)
01 推出系统前的时间处理 --- 实现监听和处理程序退出事件的功能
//视图已经加载过时调用
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//获得应用程序的单例对象,该对象的核心作用是提供了程序运行期间的控制和协作工作。每个程序在运行期间,必须有且仅有该对象的一个实例
UIApplication *app = [UIApplication sharedApplication];
//通知中心时基础框架的子系统。在本例中,它向所有监听程序退出事件的对象,广播消息
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
}
//创建一个方法,时程序在退出前,保存用户数据。
-(void)applicationWillResignActive:(id)sender {
//以游戏应用为例,此外一般用来保存场景、英雄状态等信息,也可以截取当前游戏界面,作为游戏的下次启动画面
NSLog(@">>>>>>>>>>>>>>>>>>>>>saving data before exit");
}
**********************************************************************************************************************************************************************************************************************************
02 检测App是否首次运用 --- NSUserDefaults的使用,它常被用于存储程序的配置数据.
(当你关闭程序之后,再次打开程序时,之前存储的数据,依然可以从NSUserDefaults里读取.)
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//获得变量的布尔值,当程序首次启动时,由于从未设置过此变量,所以它的值时否
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {
//讲变量赋值为真
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunched"];
//使用同步方法,立即保存修改
[[NSUserDefaults standardUserDefaults] synchronize];
}
else {
//如果不是第一次启动程序,则设置变量的布尔值为否
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunched"];
//使用同步方法,立即保存修改
[[NSUserDefaults standardUserDefaults] synchronize];
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunched"]) {
//对于首次运行的程序,可以根据需求,进行各种初始工作。这里使用一个简单的弹出窗口.
UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"It's the first show." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
[alerView show];
}
else {
UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"Hello Again" message:@"It's not the first show." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
[alerView show];
}
}
**********************************************************************************************************************************************************************************************************************************
03 读取和解析Plist属性列表文件
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"demoPlist" ofType:@"plist"];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
//将字典转换为字符串对象
NSString *message = [data description];
//注意delegate的对象使用 ——wind(贾)
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Plist Content" message:message delegate:message cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
**********************************************************************************************************************************************************************************************************************************
04 通过代码创建Plist文件 --- 通过编码方式,创建属性列表文件
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//初始化一个可变字典对象,作为属性列表内容的容器.
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
//设置属性列表文件的内容
[data setObject:@"Bruce" forKey:@"Name"];
[data setObject:[NSNumber numberWithInt:40] forKey:@"Age"];
//获得文档文件夹路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *plistPath1 = [paths objectAtIndex:0];
//生成属性列表文件的实际路径
NSString *filename = [plistPath1 stringByAppendingPathComponent:@"demoPlist.plist"];
//将可变字典对象,写入属性列表文件.
[data writeToFile:filename atomically:YES];
//读取并显示属性列表文件
NSMutableDictionary *data2 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
NSString *message = [data2 description];
//使用信息弹出窗口,显示属性列表文件的所有内容
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Plist Content" message:message delegate:message cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
05 SQLite数据库和表的创建 --- 数据库表格的创建,和数据的插入 (Attentiong:Add A Framework( libsqpite3.tbd))
//////////////////////
ViewController.h文件中:
//////////////////////
#import <UIKit/UIKit.h>
#import <sqlite3.h> //数据框架头文件
@interface ViewController : UIViewController
//创建一个数据库对象的属性
@property(assign,nonatomic)sqlite3 *database;
//打开数据库
-(void)openDB;
//用来创建数据库表格
-(void)createTestList;
//用来往表格里添加数据
-(void)insertTable;
ViewController.m文件中:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//调用执行数据库语句命令,用来执行非查询的数据库语句。最后在视图加载完成后执行各方法.
//首先打开或创建数据库
[self openDB];
//然后创建数据库中的表格
[self createTestList];
//再往表格里添加相关数据。点击 运行,打开模拟器预览项目
[self insertTable];
}
//新建一个方法,用来存放数据库文件
-(NSString *)dataFilePath {
//获得项目的文档目录
NSArray *myPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *myDocPath = [myPaths objectAtIndex:0];
//创建一个字符串,描述数据库的存放路径
NSString *filename = [myDocPath stringByAppendingPathComponent:@"data.db"];
NSLog(@"%@",filename);
return filename;
}
//创建一个方法,用来打开数据库
-(void)openDB {
//获得数据库路径
NSString *path = [self dataFilePath];
//然后打开数据库,如果数据库不存在,则创建数据库.
sqlite3_open([path UTF8String], &_database);
}
//添加一个方法,用来创建数据库中的表
-(void)createTestList {
//创建一条sql语句,用来在数据库里,创建一个表格.
const char *createSql = "create table if not exists people(ID INTEGER PRIMARY KEY AUTOINCREMENT,peopleId int,name test,age int)";
//第三个参数,是这条语句执行之后的回调函数。第四个参数,是传递给回调函数使用的参数。第五个参数是错误信息
sqlite3_exec(_database, createSql, NULL, NULL, NULL);
}
//添加一个方法,用来往表格里添加数据.
-(void)insertTable {
//创建一条sql语句,用来在数据库表里,添加一条记录
const char *insertSql = "INSERT INTO testTable(peopleId,name,age) VALUES(1,'John',28)";
sqlite3_exec(_database, insertSql, NULL, NULL, NULL);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
**********************************************************************************************************************************************************************************************************************************
06 SQLite数据库的删改查操作 --- 数据库记录的查询,修改和删除操作
//////////////////////
ViewController.h文件中:
//////////////////////
#import <UIKit/UIKit.h>
#import <sqlite3.h> //数据框架头文件
@interface ViewController : UIViewController
//创建一个数据库对象的属性
@property(assign,nonatomic)sqlite3 *database;
//打开数据库
-(void)openDB;
//用来创建数据库表格
-(void)createTestList;
//用来往表格里添加数据
-(void)insertTable;
///////////////////////////
// 本节内容: 数据库记录的查询,修改和删除操作
//添加一个方法,用来查询数据
-(void)queryTable;
//添加一个方法,用来删除数据
-(void)deleteTable;
//添加一个方法,用来更新数据
-(void)updateTable;
//////////////////////
ViewController.m文件中:
//////////////////////
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
/*
1.
//执行查询方法,点击 运行
[self queryTable];
*/
/*
//1.
// [self updateTable];
//2.
[self queryTable];
*/
/*
修改代码,演示数据库记录删除功能
*/
//1.
// [self deleteTable];
//2.
[self queryTable];
/////////////////////////////////////////////
}
//新建一个方法,用来存放数据库文件
-(NSString *)dataFilePath {
//获得项目的文档目录
NSArray *myPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *myDocPath = [myPaths objectAtIndex:0];
//创建一个字符串,描述数据库的存放路径
NSString *filename = [myDocPath stringByAppendingPathComponent:@"data.db"];
NSLog(@"%@",filename);
return filename;
}
//创建一个方法,用来打开数据库
-(void)openDB {
//获得数据库路径
NSString *path = [self dataFilePath];
//然后打开数据库,如果数据库不存在,则创建数据库.
sqlite3_open([path UTF8String], &_database);
}
//添加一个方法,用来创建数据库中的表
-(void)createTestList {
//创建一条sql语句,用来在数据库里,创建一个表格.
const char *createSql = "create table if not exists people(ID INTEGER PRIMARY KEY AUTOINCREMENT,peopleId int,name test,age int)";
//第三个参数,是这条语句执行之后的回调函数。第四个参数,是传递给回调函数使用的参数。第五个参数是错误信息
sqlite3_exec(_database, createSql, NULL, NULL, NULL);
}
//添加一个方法,用来往表格里添加数据.
-(void)insertTable {
//创建一条sql语句,用来在数据库表里,添加一条记录
const char *insertSql = "INSERT INTO testTable(peopleId,name,age) VALUES(1,'John',28)";
sqlite3_exec(_database, insertSql, NULL, NULL, NULL);
}
//////////////////////////////////////////
-(void)queryTable {
//首先打开数据库
[self openDB];
//创建一条语句,用来查询数据库记录
const char *selectSql = "select peopelId, name from people";
//sqlite操作二进制数据,需要用一个辅助的数据类型:sqlite3_stmt,这个数据类型,记录了一个sql语句
sqlite3_stmt *statement;
//sqlite3_prepare_v2函数,用来完成sql语句的解析,第三个参数的含义是前面sql语句的长度,-1表示自动计算它的长度
if (sqlite3_prepare_v2(_database, selectSql, -1, &statement, nil) == SQLITE_OK) {
//当函数sqlite3_step返回值为SQLITE_ROW时,表明数据记录集中,还包含剩余数据,可以继续进行便利操作
while (sqlite3_step(statement) == SQLITE_ROW) //SQLITE_OK SQLITE_ROW
{
//接受数据为整形的数据库记录
int _id = sqlite3_column_int(statement, 0);
//接受数据为字符串类型的数据库记录
NSString *name = [[NSString alloc] initWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding];
//在控制台输出查询到的数据
NSLog(@">>>>>>>>>>>>>>>>Id: %i, >>>>>>>>>>>>>>>>Name: %@",_id,name);
}
}
}
//创建一个方法,用来更新数据库里的数据
-(void)updateTable {
//首先打开数据库
[self openDB];
//用来创建一条语句,用来更新数据库记录
const char *sql = "update peoplt set name = 'Peter' WHERE people = 1";
sqlite3_exec(_database, sql, NULL, NULL, NULL);
//操作结束后,关闭数据库
sqlite3_close(_database);
}
//创建一个方法,用来删除数据库里的数据
-(void)deleteTable {
//首先打开数据库
[self openDB];
//创建一条语句,用来删除数据库记录
const char *sql = "DELETE FROM people where peopleId = 1";
sqlite3_exec(_database, sql, NULL, NULL, NULL);
}
**********************************************************************************************************************************************************************************************************************************
07 NSKeyedArchiver存储和解析数据
(1) 创建以Car类;
//////////////////////
Car.h文件中:
//////////////////////
#import <Foundation/Foundation.h>
//添加NSCoding 协议,用来支持数据类和数据流间的编码和解码。通过继承NSCopying协议,使数据对象支持拷贝.
@interface Car : NSObject<NSCoding,NSCopying>
//给当前类添加2个属性
@property (nonatomic,retain)NSString *brand;
@property (nonatomic,retain)NSString *color;
@end
//////////////////////
Car.m文件中:
//////////////////////
#import "Car.h"
@implementation Car
//然后,添加一个协议方法,用来对模型对象进行序列化操作.
-(void)encodeWithCoder:(NSCoder *)aCoder {
//对2个属性进行编码操作
[aCoder encodeObject:_brand forKey:@"_brand"];
[aCoder encodeObject:_color forKey:@"_color"];
}
//接着添加另一个来自协议的方法,用来对模型对象进行反序列化操作
-(id)initWithCoder:(NSCoder *)aDecoder {
if (self != [super init]) {
_brand = [aDecoder decodeObjectForKey:@"_brand"];
_color = [aDecoder decodeObjectForKey:@"_color"];
}
return self;
}
//实现NSCoping协议的copyWithZone方法,用来响应拷贝消息
-(id)copyWithZone:(NSZone *)zone {
Car *car = [[[self class] allocWithZone:zone] init];
car.brand = [self.brand copyWithZone:zone];
car.color = [self.color copyWithZone:zone];
return car;
}
///////////////////////////
ViewController.m文件中:
///////////////////////////
#import "ViewController.h"
#import "Car.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CGRect rect = CGRectMake(80, 100, 150, 30);
//创建一个按钮,点击按钮会新建一个Car对象,并把该对象归档
UIButton *initData = [[UIButton alloc] initWithFrame:rect];
//设置按钮的背景颜色为紫色
[initData setBackgroundColor:[UIColor purpleColor]];
//设置按钮标题文字
[initData setTitle:@"Initialize data" forState:UIControlStateNormal];
//设置按钮绑定事件
[initData addTarget:self action:@selector(initData) forControlEvents:UIControlEventTouchUpInside];
CGRect rect2 = CGRectMake(80, 200, 150, 30);
//接着创建另一个按钮,点击按钮会解析已归档的对象
UIButton *loadData = [[UIButton alloc] initWithFrame:rect2];
[loadData setBackgroundColor:[UIColor purpleColor]];
[loadData setTitle:@"Load data" forState:UIControlStateNormal];
[loadData addTarget:self action:@selector(loadData) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:initData];
[self.view addSubview:loadData];
}
//新建一个方法,用来设定归档对象的保存路径
-(NSString *)fileDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"archiveFile"];
}
//创建一个方法,用来初始化对象,并将对象归档
-(void)initData {
Car *car = [[Car alloc] init];
car.brand = @"Apple";
car.color = @"White";
NSMutableData *data = [[NSMutableData alloc] init];
//初始化一个归档对象,用来处理对象的归档
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:car forKey:@"dataKey"];
//完成归档对象的编码操作
[archiver finishEncoding];
//将归档后的数据,保存到磁盘上
[data writeToFile:[self fileDirectory] atomically:YES];
//创建一个窗口,用来提示归档成功
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Information" message:@"Success to initialize data." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
//创建一个方法,用来解析对象
-(void)loadData {
NSString *filePath = [self fileDirectory];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
Car *car = [unarchiver decodeObjectForKey:@"dataKey"];
//完成解码操作
[unarchiver finishDecoding];
NSString *info = [NSString stringWithFormat:@"Car Brand:%@\nCar Color:%@",car.brand,car.color];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Information" message:info delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
**********************************************************************************************************************************************************************************************************************************
08 使用MD5加密数据 --- 系统自带的md5加密功能(Attention:Add a framework(libcommonCrypto.tbd))
ViewController.m文件中:
#import "ViewController.h"
#import <CommonCrypto/CommonCrypto.h> //加密功能头文件
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//定义一个字符串对象
NSString *str = @"Hello Apple";
//将字符串对象转换成C语言字符串
const char *representation = [str UTF8String];
//创建一个标准长度的字符串
unsigned char md5[CC_MD5_DIGEST_LENGTH];
//对C语言字符串进行加密,并将结果存入变量
CC_MD5(representation, strlen(representation), md5);
//创建一个可变的字符串变量
NSMutableString *mutableStr = [NSMutableString string];
for (int i = 0; i < 16; i ++) {
//通过遍历该变量,将加密后的结果,存入可变字符串变量.
[mutableStr appendFormat:@"%02X",md5[i]];
}
//使用警告窗口对象,显示加密后的结果.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"MD5" message:mutableStr delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
iOS - 文件与数据(File & Data)的更多相关文章
- IOS学习:ios中的数据持久化初级(文件、xml、json、sqlite、CoreData)
IOS学习:ios中的数据持久化初级(文件.xml.json.sqlite.CoreData) 分类: ios开发学习2013-05-30 10:03 2316人阅读 评论(2) 收藏 举报 iOSX ...
- iOS - 文件操作(File Operating)
1. 沙盒 & NSData /*_______________________________获取沙盒路径_________________________________________* ...
- iOS 写入文件保存数据的方式
在iOS开发过程中,不管是做什么应用,都会碰到数据保存的问题.将数据保存到本地,能够让程序的运行更加流畅,不会出现让人厌恶的菊花形状,使得用户体验更好.下面介绍一下数据保存的方式: 1.NSKeye ...
- [ios]ios读写文件本地数据
参考:http://blog.csdn.net/tianyitianyi1/article/details/7713103 ios - Write写入方式:永久保存在磁盘中.具体方法为:第一步:获得文 ...
- How to: Implement File Data Properties 如何:实现文件数据属性
This topic demonstrates how to implement a business class with a file data property and a file colle ...
- ios开发 json数据文件的存取
将Json存进本地文件夹 NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomai ...
- Android中使用File文件进行数据存储
Android中使用File文件进行数据存储 上一篇学到使用SharedPerences进行数据存储,接下来学习一下使用File进行存储 我们有时候可以将数据直接以文件的形式保存在设备中, 例如:文本 ...
- ios 文件上传, post数据
转自:http://www.maxiaoguo.com/clothes/267.html 一.文件下载 获取资源文件大小有两张方式 1. HTTP HEAD方法 NSMutableURLRequest ...
- iOS - NetRequest 网络数据请求
1.网络请求 1.1 网络通讯三要素 1.IP 地址(主机名): 网络中设备的唯一标示.不易记忆,可以用主机名(域名). 1) IP V4: 0~255.0~255.0~255.0~255 ,共有 2 ...
随机推荐
- 三,对于printf函数和C语言编程的初步拓展
前面说过了,任何程序都要有输出,所以printf函数是一个很重要的函数,所以有必要在学变量之前先拓展一下. 其实编程就是用计算机语言说话,一句一句地说,只要语法没错就能运行,至于能实现什么功能,就看编 ...
- 赋值容器winform 根据NAME查找控件
每日一贴,今天的内容关键字为赋值容器 foreach (Control c in this.panel1.Controls) { if (c is TextBox && c.Name ...
- Educational Codeforces Round 2 C. Make Palindrome 贪心
C. Make Palindrome Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/600/pr ...
- Codeforces Round #192 (Div. 1) C. Graph Reconstruction 随机化
C. Graph Reconstruction Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/3 ...
- CODEFORCE 246 Div.2 B题
题目例如以下: B. Football Kit time limit per test 1 second memory limit per test 256 megabytes input stand ...
- 高级I/O之STREAMS
http://en.wikipedia.org/wiki/STREAMS STREAMS(流)是系统V提供的构造内核设备驱动程序和网络协议包的一种通用方法,对STREAMS进行讨论的目的是为了理解系统 ...
- Android N分屏模式Activity生命周期的变化
昨天Google发布了Android N Preview, balabala....我是用模拟器去验证的, 通过长按多任务窗口(口)进入分屏模式, 这里只进行了简单的测试, 不排除通过配置哪个参数, ...
- C. Guess Your Way Out!
C. Guess Your Way Out! time limit per ...
- java io文件学习笔记
File f = new file("D:"+File.separator+"test.txt"); File.separator跨系统文件分隔符 f.crea ...
- ng中用$http接后台接口的异步坑
最近笔者在一个项目中用ng去接后台的接口.因为前后端都是新手,前端的不懂后台,且没有经验:后端的不懂前端,也没有经验,然后接口bug百出,文档写得乱.一个接口,后台改了三次,我也是寸步难行. 首先来看 ...