iOS

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:%@ Car 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];

}

喜欢请赞赏一下啦^_^

微信赞赏

支付宝赞赏

原文地址:https://www.cnblogs.com/share-iOS/p/5816388.html