网络封装
#import <Foundation/Foundation.h>
@class NetWorkRequest;
// 网络请求成功block
typedef void(^NetworkRequestSuccessedHandler)(void);
// 网络请求失败block
typedef void(^NetworkRequestFailedHandler)(NSError *error);
// 网络请求进度block
typedef void(^NetworkRequestProgressHandler)(NSInteger progress);
@protocol NetWorkRequestDelegate <NSObject>
@optional
//network请求成功
- (void)netWorkRequest:(NetWorkRequest *)request SuccessfulReceiveData:(NSData *)data;
//network请求失败
- (void)netWorkRequest:(NetWorkRequest *)request didFailed:(NSError *)error;
//获取network下载进度
- (void)netWorkRequest:(NetWorkRequest *)request withProgress:(CGFloat)progress;
@end
@interface NetWorkRequest : NSObject<NSURLConnectionDataDelegate>
@property (nonatomic,assign) id<NetWorkRequestDelegate> delegate;
//声明两个方法,对外提供接口,分别实现GET请求方式和POST请求方式
//实现GET请求
- (void)requestForGETWithUrl:(NSString *)urlString;
//实现POST请求
- (void)requestForPOSTWithUrl:(NSString *)urlString postData:(NSData *)postData;
//取消网络请求
- (void)cancelRequest;
// 使用block实现网络请求结果回调
- (void)networdRquestSuccessedHandler:(NetworkRequestSuccessedHandler)successedHandler failedHandler:(NetworkRequestFailedHandler)failedHandler progressHandler:(NetworkRequestProgressHandler)progressHandler;
@end
.mmmmmmmmmmmm
#import "NetWorkRequest.h"
@interface NetWorkRequest ()
{
CGFloat _totalLength;
}
@property (nonatomic,retain) NSMutableData * receiveData;
@property (nonatomic,retain) NSURLConnection * connection;
@end
@implementation NetWorkRequest
- (void)dealloc
{
self.receiveData = nil;
self.connection = nil;
// [super dealloc];
}
//实现GET请求
- (void)requestForGETWithUrl:(NSString *)urlString
{
//封装URL对象
NSURL * url = [NSURL URLWithString:urlString];
//创建网络请求
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
//设置GET请求
[request setHTTPMethod:@"GET"];
//建立异步连接,使用设置delegate方式实现
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
//实现POST请求
- (void)requestForPOSTWithUrl:(NSString *)urlString postData:(NSData *)postData
{
//封装URL对象
NSURL * url = [NSURL URLWithString:urlString];
//创建网络请求
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
//设置POST请求
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
[request setValue:@"" forHTTPHeaderField:@"Accept-Encoding"];
//建立异步连接,使用设置delegate方式实现
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
// NSURLConnection sendAsynchronousRequest:request queue:<#(NSOperationQueue *)#> completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// }
}
//取消网络请求
- (void)cancelRequest
{
[_connection cancel];
self.connection = nil;
self.delegate = nil;
}
- (void)networdRquestSuccessedHandler:(NetworkRequestSuccessedHandler)successedHandler failedHandler:(NetworkRequestFailedHandler)failedHandler progressHandler:(NetworkRequestProgressHandler)progressHandler
{
}
#pragma mark ------------------ 异步连接代理方法 网络连接状态 -------------------
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"error = %@",error);
if ([_delegate respondsToSelector:@selector(netWorkRequest:didFailed:)]) {
[_delegate netWorkRequest:self didFailed:error];
}
self.receiveData = nil;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpURLResponse = (NSHTTPURLResponse *)response;
NSLog(@"response = %@",httpURLResponse.allHeaderFields);
// _totalLength = [httpURLResponse.allHeaderFields ];
NSLog(@"response header = %lu",(unsigned long)[httpURLResponse description].length );
self.receiveData = [NSMutableData data];
_totalLength = [response expectedContentLength];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_receiveData appendData:data];
//计算当前的下载进度
CGFloat progress = _receiveData.length/_totalLength;
//通知代理,执行代理方法,获取当前的下载进度
if ([_delegate respondsToSelector:@selector(netWorkRequest:withProgress:)]) {
[_delegate netWorkRequest:self withProgress:progress];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if ([_delegate respondsToSelector:@selector(netWorkRequest:SuccessfulReceiveData:)]) {
[_delegate netWorkRequest:self SuccessfulReceiveData:_receiveData];
}
self.receiveData = nil;
}
@end
数据持久化
文件读写
// //1.获取沙盒文件的主路径 方法名:
// NSLog(@"home = %@",NSHomeDirectory());
//
// //1.获取Documents的路径, //主路径 拼接 子文件夹
// NSLog(@"documents = %@",[NSHomeDirectory() stringByAppendingString:@"/Documents"]);
// //拼接文件夹名字
// NSLog(@"documents = %@",[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]);
//
// //获取沙盒中文件的路径
// NSArray * files = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
// NSLog(@"-------files-----%@",files.lastObject);
//
//
// //获取tmp 文件夹的路径
// NSLog(@"------tem = ----- %@",NSTemporaryDirectory());
//
//
// //获取文件包(.app)的路径 ---------NSBundle 获取的应用程序包文件及其子文件夹 只能读取 不能修改 其他的文件可以修改
// NSString * filePath = [[NSBundle mainBundle] bundlePath];
// NSLog(@"---------------filePath = %@",filePath);
// //获取包里的可执行文件,
// NSString * executablePath = [[NSBundle mainBundle] executablePath];
// NSLog(@"----------- executablePath = %@",executablePath);
//存储一个字符串
//数据持久化过程:
//1.获取存储文件的上一级路径
NSString * documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
//2.拼接完整的文件夹存储路径
NSString * filePath = [documents stringByAppendingPathComponent:@"text.text"];
//3.存储数据
NSString * saveString = @"lanou";
[saveString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
//从文件中,读取字符串对象
NSString * readString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"readString = %@",readString);
// //获取存储文件的上级路径
// NSString * documents2 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// //拼接文件的完整了路径
// NSString * filePath2 = [documents2 stringByAppendingString:@"xiaoke.text"];
// // 创建数据 并存储
// NSString * saveString2 = @"xioake";
//数组对象,存入文件
NSArray * nameArray = @[@"左友东",@"许珍珍",@"吴凯"];
//
NSString * caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//拼接完整字符串路径
NSString * filePathOfCaches = [caches stringByAppendingString:@"names.plist"];
//写入 给要写入的对象发送写入消息, 给出完整路径,
[nameArray writeToFile:filePathOfCaches atomically:YES];
//读取数组
NSArray * readArray = [NSArray arrayWithContentsOfFile:filePathOfCaches];
NSLog(@"read array = %@",readArray);
//字典对象,存入文件
NSDictionary * personDic = @{@"name": @"xiaoke",
@"sex":@"nan"};
NSString * tmp = NSTemporaryDirectory();
NSString * tmpFilePath = [tmp stringByAppendingPathComponent:@"dic.plist"];
[personDic writeToFile:tmpFilePath atomically:YES];
//字典读取
NSDictionary * readPersonDic = [NSDictionary dictionaryWithContentsOfFile:tmpFilePath];
NSLog(@"read person dic = %@",readPersonDic);
//将字典从dic.plist中读取出来,修改其中某个value,然后从新写入dic.plist文件
NSMutableDictionary * personM_Dic = [NSMutableDictionary dictionaryWithContentsOfFile:tmpFilePath];
[personM_Dic setValue:@"小可" forKey:@"name"];
[personM_Dic writeToFile:tmpFilePath atomically:YES];
//NSData数据读写
UIImage * image = [UIImage imageNamed:@"cellImage"];
NSData * saveData = UIImagePNGRepresentation(image);
NSString * imageFilePath = [documents stringByAppendingPathComponent:@"newCellImage.array"];
[saveData writeToFile:imageFilePath atomically:YES];
NSData * readData = [NSData dataWithContentsOfFile:imageFilePath];
UIImage * readImage = [UIImage imageWithData:readData];
UIImage * readImage2 = [UIImage imageWithContentsOfFile:imageFilePath];
UIImageView * ima = [[UIImageView alloc] initWithImage:readImage2];
[self.window addSubview:ima];
[ima release];
//读取应用程序包(工程)中得图像,有两种方式
//第一种, 读取后就存放在内存中, 二次读取速度快 享元设计模式
[UIImage imageNamed:@"cellImage"];
//第二种, 没次都从 包(.app)中读取, 速度稍微慢,但不持续占内存
[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cellImage" ofType:@"png"]];
归档反归档
//序列化,编码
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:@"NameKey"];
[aCoder encodeInt:_age forKey:@"AgeKey"];
}
//反序列化, 解码
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"NameKey"];
self.age = [aDecoder decodeIntForKey:@"AgeKey"];
}
return self;
}
- (void)didClickArchiverPersonButtonAction
{
ABPerson * person_xiaoke = [[ABPerson alloc]init];
person_xiaoke.name = @"Pack";
person_xiaoke.age = 24;
ABPerson * person_jiaozhu = [[ABPerson alloc] init];
person_jiaozhu.name = @"Siri";
person_jiaozhu.age = 23;
NSArray * archiverArray = @[person_xiaoke,person_jiaozhu];
[person_jiaozhu release];
[person_xiaoke release];
NSMutableData * archiverData = [NSMutableData data];
NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:archiverData];
[archiver encodeObject:archiverArray forKey:@"personArray"];
[archiver finishEncoding];
NSString * file = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
NSString * filePath = [file stringByAppendingPathComponent:@"archiverArray.arr"];
[archiverData writeToFile:filePath atomically:YES];
[archiver release];
}
- (void)didClickUnarchiverPersonButtonAction
{
NSString * file = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
NSString * filePath = [file stringByAppendingPathComponent:@"archiverArray.arr"];
NSData * unarchiverData = [NSData dataWithContentsOfFile:filePath];
NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:unarchiverData];
NSArray * unarchiverArray = [unarchiver decodeObjectForKey:@"personArray"];
[unarchiver finishDecoding];
for (ABPerson * person in unarchiverArray) {
NSLog(@"name = %@,age = %d",person.name,person.age);
}
}
//数组序列化Button 响应方法
- (void)didClickArchiverArrayButtonAction
{
ABPerson * person_x = [[ABPerson alloc]init];
person_x.name = @"船长";
person_x.age = 24;
ABPerson * person_jiaozhu = [[ABPerson alloc]init];
person_jiaozhu.name = @"教主";
person_jiaozhu.age = 24;
NSArray * personArray = @[person_xiaoke,person_jiaozhu];
[person_jiaozhu release];
[person_x release];
NSMutableData * archiveM_Data = [[NSMutableData alloc]init];
NSKeyedArchiver * keyedArchiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:archiveM_Data];
[keyedArchiver encodeObject:personArray forKey:@"personArray"];
[keyedArchiver finishEncoding];
NSString * file = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
NSString * filePath = [file stringByAppendingPathComponent:@"personArray.array"];
[archiveM_Data writeToFile:filePath atomically:YES];
[archiveM_Data release];
[keyedArchiver release];
}
//数组反序列化Button 响应方法
- (void)didClickUnarchiverArrayButtonAction
{
NSString * file = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString * filePath = [file stringByAppendingPathComponent:@"personArray.array"];
NSData * unarchiverData = [NSData dataWithContentsOfFile:filePath];
NSKeyedUnarchiver * keyedUnarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:unarchiverData];
NSArray * personArray = [keyedUnarchiver decodeObjectForKey:@"personArray"];
[keyedUnarchiver finishDecoding];
[keyedUnarchiver release];
for (ABPerson * person in personArray) {
NSLog(@"name = %@, age = %d",person.name,person.age);
}
}
- (void)didClickArchiverButtonAction
{
//对复杂的数据对象进行写入资料,原理:复杂的数据对象序列化为NSData,将NSData写入文件,实现数据持久化
/*********************************
* 1.自定义复杂的数据类型,例如:ABPerson, (
* (1)ABPerson 必须实现NSCoding协议的方法
* (2)ABPerson 中得实例变量或属性(对象类型),也必须实现NSCoding协议的方法
(3)ABPerson 中得基本数据类型没有过多限制
2. 创建一个序列化工具对象
3. 对复杂对象进行序列化
4. 结束序列化
5. 写入Data
***************************************/
NSMutableData * archiverM_Data = [NSMutableData data];
NSKeyedArchiver * keyedArchiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:archiverM_Data];
//3, 对复杂对象进行序列化
ABPerson * person = [[ABPerson alloc] init];
person.name = @"xiaohei";
person.age = 24;
[keyedArchiver encodeObject:person forKey:@"PersonKey"];
//4.结束序列化
[keyedArchiver finishEncoding];
//NSData写入
NSString * file_person = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString * filePath_person = [file_person stringByAppendingPathComponent:@"person.data"];
[archiverM_Data writeToFile:filePath_person atomically:YES];
[keyedArchiver release];
[person release];
}
- (void)didClickUnarchiverButtonAction
{
/************************
//通过读取文件,实例化复杂数据对象 // NSData
1.创建一个反序列化工具对象
2.
********************/
//1.
NSString * file_person = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString * filePath_person = [file_person stringByAppendingPathComponent:@"person.data"];
NSData * unarchiverData = [NSData dataWithContentsOfFile:filePath_person];
NSKeyedUnarchiver * keyUnarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:unarchiverData];
ABPerson * person = [keyUnarchiver decodeObjectForKey:@"PersonKey"];
[keyUnarchiver finishDecoding];
NSLog(@"name = %@, age = %d",person.name,person.age);
[keyUnarchiver release];
}
SQLite数据库
DataBase
#import <Foundation/Foundation.h>
#import <sqlite3.h>
@interface DataBase : NSObject
//打开数据库
+ (sqlite3 *)openDataBase;
//关闭数据库
+ (BOOL)closeDataBase;
@end
.mmmmmmmmmmmmmmmmmmm
#import "DataBase.h"
static sqlite3 * db = nil;
@implementation DataBase
+ (NSString *)document
{
NSString * file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
return file;
}
//打开数据库
+ (sqlite3 *)openDataBase
{
//判断数据库是否打开,如果打开直接返回
if (db) {
return db;
}
//找到文件完整路径
NSString * filePath = [[DataBase document] stringByAppendingPathComponent:@"Contacts.sqlite"];
//创建NSFileManager对象
NSFileManager * fileManager = [NSFileManager defaultManager];
//判断沙盒中是否有Contacts.sqlite
if (![fileManager fileExistsAtPath:filePath]) {
//如果没有Contacts.sqlite文件,则创建数据库文件
int result = sqlite3_open([filePath UTF8String], &db);
//
if (result == SQLITE_OK) {
//如果创建数据库成功,先创建一个 表的 SQL语法,
NSString * sql = @"CREATE TABLE 'Contacts'('name' TEXT NOT NULL,'sex' TEXT DEFAULT 不男不女,'age' INTEGER DEFAULT 18,'number' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'icon' BLOB)";
//给数据库添加表
int resultSQL = sqlite3_exec(db, [sql UTF8String], NULL, NULL, NULL);
if (resultSQL == SQLITE_OK) {
return db;
}
}
}
//如果沙盒中有数据库文件,则打开数据库
int result = sqlite3_open([filePath UTF8String], &db);
if (result == SQLITE_OK) {
return db;
}
return nil;
}
//关闭数据库
+ (BOOL)closeDataBase
{
int result = sqlite3_close(db);
if (result == SQLITE_OK) {
return YES;
}
return NO;
}
@end
DataManager
#import <Foundation/Foundation.h>
@interface DataManager : NSObject
+ (DataManager *)shareInstance;
//插入数据
- (void)insertWithName:(NSString *)name sex:(NSString *)sex age:(NSInteger)age number:(NSInteger)number image:(UIImage *)image;
//删除数据
- (void)deleteDataWithNumber:(NSInteger)number;
//修改数据
- (void)updataWithNumber:(NSInteger)number name:(NSString *)name;
//查找数据
- (NSMutableArray *)selectAllDataWithName;
//查找某个Number 的所有数据
- (NSDictionary *)selectOneContactsDicWithNumber:(NSInteger)number;
@end
.mmmmmmmmmmmmmmmmmmmmmmmm
#import "DataManager.h"
#import "DataBase.h"
@implementation DataManager
+ (DataManager *)shareInstance
{
static DataManager * _dataManager = nil;
@synchronized(self){
if (!_dataManager) {
_dataManager = [[DataManager alloc]init];
}
}
return _dataManager;
}
//插入数据
- (void)insertWithName:(NSString *)name sex:(NSString *)sex age:(NSInteger)age number:(NSInteger)number image:(UIImage *)image
{
//获取数据库
sqlite3 * db = [DataBase openDataBase];
//创建跟随指针stmt
sqlite3_stmt * stmt = nil;
//创建需要执行的SQL语法
NSString * sql = @"INSERT INTO Contacts (name,sex,age,number,icon) values(?,?,?,?,?)";
//验证SQL语句
int result = sqlite3_prepare(db, [sql UTF8String], -1, &stmt, NULL);
NSLog(@"result ========= %d",result);
if (result == SQLITE_OK) {
//绑定数据
sqlite3_bind_text(stmt, 1, [name UTF8String], -1, NULL);
sqlite3_bind_text(stmt, 2, [sex UTF8String], -1, NULL);
sqlite3_bind_int(stmt, 3, (int)age);
sqlite3_bind_int(stmt, 4, (int)number);
NSData * imageData = UIImagePNGRepresentation(image);
const void * bytes = [imageData bytes];
int length = (int)[imageData length];
sqlite3_bind_blob(stmt, 5, bytes, length, NULL);
//单步执行SQL语句
sqlite3_step(stmt);
//释放stmt
sqlite3_finalize(stmt);
}
}
//删除数据
- (void)deleteDataWithNumber:(NSInteger)number
{
//获取数据库
sqlite3 * db = [DataBase openDataBase];
//创建跟随指针,
sqlite3_stmt * stmt = nil;
//创建需要执行的SQL语句
NSString * deleteSQL = @"DELETE FROM Contacts WHERE number = ?";
//验证SQL语句
int result = sqlite3_prepare(db, [deleteSQL UTF8String], -1, &stmt, NULL);
NSLog(@"result ========= %d",result);
if (result == SQLITE_OK) {
//绑定数据
sqlite3_bind_int(stmt, 1, (int)number);
//删除数据 单步执行SQL语句
sqlite3_step(stmt);
//释放跟随指针,stmt
sqlite3_finalize(stmt);
}
}
//修改数据
- (void)updataWithNumber:(NSInteger)number name:(NSString *)name
{
//获取数据库
sqlite3 * db = [DataBase openDataBase];
//创建跟随指针 stmt
sqlite3_stmt * stmt = nil;
//创建需要执行的SQL语句
NSString * updataSQL = @"UPDATE Contacts SET name = ? WHERE number = ?";
//验证SQL语句
int result = sqlite3_prepare(db, [updataSQL UTF8String], -1, &stmt, NULL);
NSLog(@"result ======== %d",result);
if (result == SQLITE_OK) {
//绑定数据
sqlite3_bind_text(stmt, 1, [name UTF8String], -1, NULL);
sqlite3_bind_int(stmt, 2, (int)number);
//单步执行SQL语句 修改数据
sqlite3_step(stmt);
//释放跟随指针,stmt
sqlite3_finalize(stmt);
}
}
//查找数据
- (NSMutableArray *)selectAllDataWithName
{
//获取数据库
sqlite3 * db = [DataBase openDataBase];
//创建跟随指针 stmt
sqlite3_stmt * stmt = nil;
//创建需要执行的SQL语句
NSString * selectSQL = @"SELECT name FROM Contacts";
//验证SQL语句
int result = sqlite3_prepare(db, [selectSQL UTF8String], -1, &stmt, NULL);
NSLog(@"result ===========%d",result);
if (result == SQLITE_OK) {
//创建数据 ,用来保存查找到得name
NSMutableArray * allNameArray = [NSMutableArray array];
//循环执行单步SQL语句,step
while (sqlite3_step(stmt) == SQLITE_ROW) {
NSString * name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)];
[allNameArray addObject:name];
}
return allNameArray;
}
return nil;
}
//查找某个Number 的所有数据
- (NSDictionary *)selectOneContactsDicWithNumber:(NSInteger)number
{
//获取数据库
sqlite3 * db = [DataBase openDataBase];
//创建跟随指针 stmt
sqlite3_stmt * stmt = nil;
//创建需要执行的SQL语句
NSString * selectSQL = @"SELECT name,sex,age,number,icon FROM Contacts WHERE number = ?";
//验证SQL语句
int result = sqlite3_prepare(db, [selectSQL UTF8String], -1, &stmt, NULL);
NSLog(@"result ====== %d",result);
if (result == SQLITE_OK) {
//绑定数据, number
sqlite3_bind_int(stmt, 1, (int)number);
//单步执行SQL语句 step
while (sqlite3_step(stmt) == SQLITE_ROW) {
NSString * name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)];
NSString * sex = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
int age = sqlite3_column_int(stmt, 2);
int number = sqlite3_column_int(stmt, 3);
const void * bytes =sqlite3_column_blob(stmt, 4);
int length = sqlite3_column_bytes(stmt, 4);
NSData * imageData = [NSData dataWithBytes:bytes length:length];
UIImage * image = [UIImage imageWithData:imageData];
//释放跟随指针,stmt
sqlite3_finalize(stmt);
NSDictionary * dic = @{@"name": name,
@"sex":sex,
@"age":[NSNumber numberWithInt:age],
@"number":[NSNumber numberWithInt:number],
@"image":image};
return dic;
}
}
return nil;
}
@end
手势处理
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
ImageView * imageView = [[ImageView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
[self.view addSubview:imageView];
[imageView release];
UIPanGestureRecognizer * panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewPanGesture:)];
[imageView addGestureRecognizer:panGesture];
[panGesture release];
// 实例变量
point = imageView.center;
}
//imageVie平移触发事件
- (void)imageViewPanGesture:(UIPanGestureRecognizer *)gesture
{
ImageView * imageView = (ImageView *)gesture.view;
CGFloat const f1 = point.x;
CGFloat const f2 = point.y;
CGPoint newPoint;
newPoint.x = f1+[gesture translationInView:imageView].x;
newPoint.y = f2+[gesture translationInView:imageView].y;
imageView.center = newPoint;
if (gesture.state == UIGestureRecognizerStateEnded) {
point = imageView.center;
}
}
XML解析
XML DOM解析(GDataXMLNode)
NSString * studentPath = [[NSBundle mainBundle] pathForResource:@"Students" ofType:@"xml"];
NSData * studentData = [NSData dataWithContentsOfFile:studentPath];
//从文档中读出完整的XML数据,在内存中形成完整的属性结构
NSError * error = nil;
GDataXMLDocument * document = [[GDataXMLDocument alloc] initWithData:studentData options:0 error:&error];
//读取XML文档数的根节点
GDataXMLElement * root = [document rootElement];
NSLog(@" root ========== %@",root);
//获取根节点students下的所有子节点
NSArray * studentArray = [root elementsForName:@"student"];
for (GDataXMLElement * student in studentArray) {
GDataXMLElement * nameElement = [student elementsForName:@"name"].lastObject;
NSString * nameString = [nameElement stringValue];
GDataXMLElement * numberElement = [student elementsForName:@"number"].lastObject;
NSString * numberString = [numberElement stringValue];
GDataXMLElement * sexElement = [student elementsForName:@"sex"].lastObject;
NSString * sexString = [sexElement stringValue];
GDataXMLElement * ageElement = [student elementsForName:@"sex"].lastObject;
NSString * ageString = [ageElement stringValue];
NSLog(@"name = %@, number = %@, sex = %@, age = %@", nameString,numberString,sexString,ageString);
}
//xpath 相对路径,(//name) 获取XML中所有name字段的 值 绝对路径 (student/name) 获取所有student下name的值
NSArray * nameArray = [root nodesForXPath:@"student/name" error:nil];
NSLog(@"name Array = %@",nameArray);
XML SAX解析
系统解析
- (void)requestWithUrlString:(NSString *)urlStr
{
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
xmlParser.delegate = self;
[xmlParser parse];
}];
}
#pragma mark - XMLParserDelegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(@"%s,%d,xxxxx = %@, qName = %@, attributes = %@",__FUNCTION__, __LINE__, elementName,qName,attributeDict);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(@"%s, %d,xxxx = %@", __FUNCTION__, __LINE__, elementName);
}
- (void)parser:(NSXMLParser *)parser didStartMappingPrefix:(NSString *)prefix toURI:(NSString *)namespaceURI
{
NSLog(@"%s,%d,xxxxx = %@",__FUNCTION__, __LINE__,prefix);
}
- (void)parser:(NSXMLParser *)parser foundComment:(NSString *)comment
{
NSLog(@"%s,%d,xxxxx = %@",__FUNCTION__, __LINE__, comment);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(@"%s,%d,xxxxx = %@",__FUNCTION__, __LINE__, string);
}
多线程
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//获取主线程对象
NSLog(@"main thread = %@",[NSThread mainThread]);
UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(130, 420, 80, 30);
[self.view addSubview:button];
self.view.backgroundColor = [UIColor lightGrayColor];
[button setTitle:@"输出" forState:UIControlStateNormal];
[button addTarget:self action:@selector(didClickButtonAction) forControlEvents:UIControlEventTouchUpInside];
UIButton * threadButton = [UIButton buttonWithType:UIButtonTypeSystem];
threadButton.frame = CGRectMake(50, 100, 200, 30);
[self.view addSubview:threadButton];
[threadButton setTitle:@"NSThread(detach)" forState:UIControlStateNormal];
[threadButton addTarget:self action:@selector(didClickThreadButtonAction) forControlEvents:UIControlEventTouchUpInside];
UIButton * invocationOperationButton = [UIButton buttonWithType:UIButtonTypeSystem];
invocationOperationButton.frame = CGRectMake(10, 150, 200, 30);
[self.view addSubview:invocationOperationButton];
[invocationOperationButton setTitle:@"invocationOperation" forState:UIControlStateNormal];
[invocationOperationButton addTarget:self action:@selector(didClickInvocationOperationButtonAction) forControlEvents:UIControlEventTouchUpInside];
UIButton * blockOperationButton = [UIButton buttonWithType:UIButtonTypeSystem];
blockOperationButton.frame = CGRectMake(10 , 190, 200, 30);
[self.view addSubview:blockOperationButton];
[blockOperationButton setTitle:@"blockOperation" forState:UIControlStateNormal];
[blockOperationButton addTarget:self action:@selector(didClickBlockOperationButtonAction) forControlEvents:UIControlEventTouchUpInside];
UIButton * operationQueueButton = [UIButton buttonWithType:UIButtonTypeSystem];
operationQueueButton.frame = CGRectMake(50, 330, 200, 30);
[self.view addSubview:operationQueueButton];
[operationQueueButton setTitle:@"operationQueue" forState:UIControlStateNormal];
[operationQueueButton addTarget:self action:@selector(didClickOperationQueueButtonAction) forControlEvents:UIControlEventTouchUpInside];
UIButton * nsobjectButton = [UIButton buttonWithType:UIButtonTypeSystem];
nsobjectButton.frame = CGRectMake(50, 370, 200, 30);
[self.view addSubview:nsobjectButton];
[nsobjectButton setTitle:@"NSObject" forState:UIControlStateNormal];
[nsobjectButton addTarget:self action:@selector(didClickNSObjectButtonAction) forControlEvents:UIControlEventTouchUpInside];
nsobjectButton.backgroundColor = [UIColor greenColor];
//定时器,自动循环执行, 自动添加到主线程的RunLoop中循环(因为viewDidLoad是在主线程中执行,因此timer对象是添加到主线程的runloop中,主线程的runloop一直处于运动状态
// [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(didClickTimerAcion) userInfo:nil repeats:YES];
// //创建一个NSTimer对象,手动添加到runloop中
// NSTimer * timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(didClickTimerAcion) userInfo:nil repeats:YES];
// [timer fire];
// [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
- (void)didClickNSObjectButtonAction
{
NSString * urlString = @"http://d.hiphotos.baidu.com/image/w%3D2048/sign=232a6514be315c6043956cefb989ca13/c83d70cf3bc79f3d3b082d31b8a1cd11738b29c2.jpg";
[self performSelectorInBackground:@selector(downloadImage:) withObject:urlString];
}
//在子线程中实现同步连接下载图片
- (void)downloadImage:(NSString *)urlString
{
@autoreleasepool {
//同步执行
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSLog(@"data = %@",data);
//从子线程发出消息,在主线程执行某些操作
[self performSelectorOnMainThread:@selector(showImage:) withObject:data waitUntilDone:YES];
}
}
//在主线程中,将子线程中下载得到的图像,显示在UIImageView上
- (void)showImage:(NSData *)data
{
UIImage * image = [UIImage imageWithData:data];
UIImageView * imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imageView];
[imageView release];
}
- (void)didClickInvocationOperationButtonAction
{
//封装好哪个对象要执行哪个方法,//
NSInvocationOperation * operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(didClickButtonAction) object:nil];
//创建操作队列 //操作队列可以暂停,暂时挂起,
NSOperationQueue * queue = [[NSOperationQueue alloc] init];
//操作对象添加到操作队列中 // 队列特点 先进先出
[queue addOperation:operation];
[operation release];
[queue release];
}
- (void)didClickBlockOperationButtonAction
{
//在子线程中需要执行的任务,当子线程开启运行状态时,才会执行
NSBlockOperation * blockOperation = [NSBlockOperation blockOperationWithBlock:^{
[self didClickButtonAction];
}];
//创建操作队列,
NSOperationQueue * queue = [[NSOperationQueue alloc] init];
// [queue addOperation:blockOperation];
[queue addOperationWithBlock:^{
[self didClickButtonAction];
}];
//操作队列的最大并发数 //同时执行的操作对象,最多同时执行3个,
[queue setMaxConcurrentOperationCount:3];
}
- (void)didClickOperationQueueButtonAction
{
}
- (void)didClickTimerAcion
{
NSLog(@"-------");
}
//创建另一个线程(子线程),帮助主线程完成某个任务
- (void)didClickThreadButtonAction
{
//创建子线程,子线程自动进入等待启动状态
//给子线程分配任务
// [NSThread detachNewThreadSelector:@selector(didClickButtonAction) toTarget:self withObject:nil];
//实例方法创建子线程,需要手动开启子线程
NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(didClickButtonAction) object:nil];
[thread start];
}
//任务 按顺序输出从 0 ~ 6553500000 的所有值
- (void)didClickButtonAction
{
//在多线程方法中需要添加自动释放池,否则会造成内存泄露,因为子线程管理的任务执行完成后,子线程会被弃用//主线程默认添加自动释放池,
@autoreleasepool {
// //主线程的runloop默认是开启的,子线程的runloop默认是关闭的,如果有需要,需要手动开启
// //如果子线程的runloop开启,子线程不会被销毁,
// [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(didClickTimerAcion) userInfo:nil repeats:YES];
// [[NSRunLoop currentRunLoop] run];
//
// //是子线程还是主线程执行
// NSLog(@"%d",[NSThread isMainThread]);
// //获取执行管理方法的线程对象
// NSThread * thread = [NSThread currentThread];
// NSLog(@"thread = %@",thread);
//
//
// //当前线程休眠10秒
// [NSThread sleepForTimeInterval:10.0f];
for (NSInteger i = 0; i < 6553500000; i++) {
NSLog(@"i = %ld",i);
}
}
}
GCD 队列
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton * globalButton = [UIButton buttonWithType:UIButtonTypeSystem];
globalButton.frame = CGRectMake(10, 100, 100, 30);
[self.view addSubview:globalButton];
[globalButton setTitle:@"Global" forState:UIControlStateNormal];
[globalButton addTarget:self action:@selector(didClickGlobalButtonAction) forControlEvents:UIControlEventTouchUpInside];
UIButton * customButton = [UIButton buttonWithType:UIButtonTypeSystem];
customButton.frame = CGRectMake(150, 100, 100, 30);
[self.view addSubview:customButton];
[customButton setTitle:@"Custom" forState:UIControlStateNormal];
[customButton addTarget:self action:@selector(didClickCustomButtonButtonAction) forControlEvents:UIControlEventTouchUpInside];
}
- (void)didClickGlobalButtonAction
{
//获取全局队列,添加任务,这个任务由全局队列创建子线程,开启执行
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalQueue, ^{
NSLog(@"%d",[NSThread isMainThread]);
//这个block执行时,是在子线程中
//建立同步连接,获取图片
NSString * urlString = @"http://d.hiphotos.baidu.com/image/w%3D2048/sign=232a6514be315c6043956cefb989ca13/c83d70cf3bc79f3d3b082d31b8a1cd11738b29c2.jpg";
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSLog(@"data = %@",data);
//图像获取成功后,将图片显示在UI上(这个任务必须在主线程完成)
//找主队列,添加任务
dispatch_async(dispatch_get_main_queue(), ^{
UIImage * image = [UIImage imageWithData:data];
UIImageView * imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imageView];
[imageView release];
});
});
}
- (void)didClickCustomButtonButtonAction
{
//自定义队列/ 创建queue, 参数1. 名字, 参数2. 并行
dispatch_queue_t myConcurrentQueue = dispatch_queue_create("xiaoke_queue", DISPATCH_QUEUE_CONCURRENT);
//添加任务
dispatch_async(myConcurrentQueue, ^{
NSString * urlString = @"http://d.hiphotos.baidu.com/image/w%3D2048/sign=232a6514be315c6043956cefb989ca13/c83d70cf3bc79f3d3b082d31b8a1cd11738b29c2.jpg";
//子线程获取数据
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
//主线程显示imageVIew
dispatch_async(dispatch_get_main_queue(), ^{
UIImage * image = [UIImage imageWithData:data];
UIImageView * imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = self.view.frame;
[self.view addSubview:imageView];
[imageView release];
});
});
dispatch_release(myConcurrentQueue);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
核心动画
View层动画
@implementation FirstViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_showImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"小白"]];
_showImageView.frame = CGRectMake(60, 30, 200, 200);
[self.view addSubview:_showImageView];
[_showImageView release];
_fromView = [[UIView alloc] initWithFrame:_showImageView.bounds];
_fromView.backgroundColor = [UIColor redColor];
[_showImageView addSubview:_fromView];
_toView = [[UIView alloc] initWithFrame:_showImageView.bounds];
_toView.backgroundColor = [UIColor greenColor];
// [_showImageView addSubview:_toView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// 使用Context实现视图的基本属性的动画效果
- (IBAction)didClickUIViewAttributeButtonAction:(id)sender {
//imageView以动画效果展示位置移动,修改center
//1. 开始设置动画 参数1:动画名字 参数2:类型空指针,给代理方法传值
[UIView beginAnimations:@"center" context:_showImageView];
//2. 动画设置
//设置动画时间
[UIView setAnimationDuration:1];
//设置动画的重复次数
// [UIView setAnimationRepeatCount:2];
//设置往返 //获取view动画开始之前的属性
[UIView setAnimationWillStartSelector:@selector(animationWillStart:context:)];
//获取view动画结束时候的属性
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
//view动画设置代理
[UIView setAnimationDelegate:self];
//设置图片中心点
_showImageView.center = CGPointMake(200, 200);
//设置动画过程中透明度
_showImageView.alpha = 0.3;
//3. 提交动画设置,开始执行动画
[UIView commitAnimations];
}
- (void)animationWillStart:(NSString *)animationID context:(void *)context
{
NSLog(@"animationID = %@",animationID);
NSLog(@"context = %@",context);
}
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
NSLog(@"animationID = %@",animationID);
NSLog(@"context = %@",context);
//动画结束时候,让图片回到原始位置
[UIView beginAnimations:@"return" context:_showImageView];
[UIView setAnimationDuration:1.0];
_showImageView.center = CGPointMake(160, 130);
_showImageView.alpha = 1;
[UIView commitAnimations];
}
- (IBAction)didClickTranslationButtonAction:(id)sender {
//使用block实现动画
[UIView animateWithDuration:1.5 animations:^{
//通过设置UIView的transform属性,实现视图的移动
if (_mySwitch.isOn == YES) {
//这个方法基于上次的transform进行设置
_showImageView.transform = CGAffineTransformTranslate(_showImageView.transform, 50, 0);
}else{
//基于原始的transform进行设置
_showImageView.transform = CGAffineTransformMakeTranslation(-50, 0);
}
}];
}
- (void)dealloc {
[_mySwitch release];
[_fromView release];
[_toView release];
[super dealloc];
}
- (IBAction)didClickRotationButtonAction:(id)sender {
[UIView animateWithDuration:1.0 animations:^{
if (_mySwitch.isOn == YES) {
// 设置动画重复两次
[UIView setAnimationRepeatCount:2];
// [UIView setAnimationsEnabled:NO];
_showImageView.transform = CGAffineTransformRotate(_showImageView.transform, M_PI/2);
}else{
_showImageView.transform = CGAffineTransformMakeRotation(M_PI);
}
} completion:^(BOOL finished) {
NSLog(@"动画完成");
}];
}
- (IBAction)didClickScaleButtonAction:(id)sender {
[UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionAutoreverse animations:^{
if (_mySwitch.isOn == YES) {
_showImageView.transform = CGAffineTransformScale(_showImageView.transform, -1.0, 1.0);
}else{
_showImageView.transform = CGAffineTransformMakeScale(0.5, 0.5);
}
} completion:^(BOOL finished) {
}];
}
- (IBAction)didClickTransitonButtonAction:(id)sender {
// if (_fromView.superview != nil) {
// [UIView transitionWithView:_showImageView duration:1.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
//
// [_fromView removeFromSuperview];
// [_showImageView addSubview:_toView];
//
// } completion:^(BOOL finished) {
//
// }];
//
// }else{
// [UIView transitionWithView:_showImageView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
// [_toView removeFromSuperview];
// [_showImageView addSubview:_fromView];
//
// } completion:nil];
//
//
// }
// [UIView transitionWithView:_showImageView duration:1.0 bbbvb animations:^{
//
// [_showImageView exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
//
// } completion:nil];
//
if (_fromView.superview != nil) {
[UIView transitionFromView:_fromView toView:_toView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromTop completion:^(BOOL finished) {
NSLog(@"???");
}];
}else{
[UIView transitionFromView:_toView toView:_fromView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromTop completion:^(BOOL finished) {
NSLog(@"ooo");
}];
}
}
@end
CoreAnimation layer层核心动画
#import "SecondViewController.h"
@interface SecondViewController ()
{
UIImageView * _showImageView;
}
@end
@implementation SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_showImageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
_showImageView.backgroundColor = [UIColor purpleColor];
[self.view addSubview:_showImageView];
[_showImageView release];
//
_showImageView.layer.masksToBounds = YES;
// _showImageView.layer.cornerRadius = 100.0;//圆角
_showImageView.layer.borderWidth = 2.0;//边框宽度
_showImageView.layer.borderColor = [UIColor greenColor].CGColor;//边框颜色
//
// _showImageView.labyer.shadowColor = [UIColor lightGrayColor].CGColor;//阴影颜色
// _showImageView.layer.shadowOffset = CGSizeMake(50, 50);//阴影偏移量
// _showImageView.layer.shadowRadius = 15;// 阴影半径
// _showImageView.layer.shadowOpacity = 1.0;// 阴影不透明度
//
//
// //锚点默认是视图的中心点,视图的旋转,缩放等操作是基于锚点操作 //position,是锚点到父视图原点的距离
// NSLog(@"anchorPoint = %@",NSStringFromCGPoint(_showImageView.layer.anchorPoint));
// NSLog(@"position = %@",NSStringFromCGPoint(_showImageView.layer.position));
//
//
//
// //给showImageView添加一个子图层
// CALayer * layer = [CALayer layer];
// layer.backgroundColor = [UIColor cyanColor].CGColor;
// [_showImageView.layer addSublayer:layer];
// layer.frame = CGRectMake(50, 50, 100, 100);
// layer.cornerRadius = 50;
//
//
//
NSLog(@"anchroPoint = %@",NSStringFromCGPoint(_showImageView.layer.anchorPoint));
NSLog(@"position = %@", NSStringFromCGPoint(_showImageView.layer.position));
_showImageView.layer.cornerRadius = 10.0f;
_showImageView.layer.borderColor = [UIColor redColor].CGColor;
_showImageView.layer.borderWidth = 10.0f;
_showImageView.layer.shadowColor = [UIColor blueColor].CGColor;
_showImageView.layer.shadowOffset = CGSizeMake(20, 20);
_showImageView.layer.shadowOpacity = 1.0f;
NSLog(@"anchorPoint = %@", NSStringFromCGPoint(_showImageView.layer.anchorPoint));
NSLog(@"position = %@",NSStringFromCGPoint(_showImageView.layer.position));
// CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
// CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"transform.scale.y"];
// CABasicAnimation *animation3 = [CABasicAnimation animationWithKeyPath:@"opacity"];
//
// CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//
// animation.values = @[
// [NSValue valueWithCGPoint:CGPointMake(100, 100)],
// [NSValue valueWithCGPoint:CGPointMake(200, 150)],
// [NSValue valueWithCGPoint:CGPointMake(100, 200)],
// [NSValue valueWithCGPoint:CGPointMake(200, 250)]
// ];
// [_showImageView.layer addAnimation:animation forKey:@"position"];
// CATransition *animation = [CATransition animation];
// [animation setDuration:1.0];
//
// // 动画过渡类型
// animation.type = kCATransitionMoveIn;
//
// // 动画过渡方向
// animation.subtype = kCATransitionFromRight;
//
// [_showImageView.layer addAnimation:animation forKey:@"transition"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)didClickCABasicButtonAction:(id)sender {
// //创建一个CABasic动画对象,参数为 需要进行动画设置的 layer的属性 名字
// CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
// [animation setDuration:1.5];
// //CABasicAnimation 提供了两个属性,fromValue 和 toValue ,设置动画过程的起始值和结束值
// animation.fromValue = (id)[UIColor yellowColor].CGColor;
// animation.toValue = (id)[UIColor blackColor].CGColor;
//
// //把创建好的动画对象添加给 layer
// [_showImageView.layer addAnimation:animation forKey:@"背景颜色"];
// CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
// [animation setDuration:3.0];
// [animation setAutoreverses:YES];
//
// animation.fromValue = [NSNumber numberWithInt:1];
// animation.toValue = [NSNumber numberWithFloat:0.0];
//
// [_showImageView.layer addAnimation:animation forKey:@"不透明度"];
//
CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"transform.scale.y"];
[animation setDuration:2.0];
[animation setAutoreverses:YES];
animation.fromValue = [NSNumber numberWithFloat:1.0];
animation.toValue = [NSNumber numberWithFloat:0.5];
[_showImageView.layer addAnimation:animation forKey:@"scale.y"];
}
- (IBAction)didClickCAKeyFromeValueButtonAction:(id)sender {
CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];//layer的属性
animation.duration = 7.0;
//设置动画关键帧
animation.values = @[
[NSValue valueWithCGPoint:CGPointMake(100, 50)],
[NSValue valueWithCGPoint:CGPointMake(200, 100)],
[NSValue valueWithCGPoint:CGPointMake(100, 150)],
[NSValue valueWithCGPoint:CGPointMake(200, 100)],
[NSValue valueWithCGPoint:CGPointMake(100, 50)]
];
[_showImageView.layer addAnimation:animation forKey:@"position"];
}
- (IBAction)didClickCAKeyFromePathButtonAction:(id)sender {
CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//创建一个空的路径对象 path
CGMutablePathRef path = CGPathCreateMutable(); //create 之后要 release
//设置路径初始点
CGPathMoveToPoint(path, NULL, 50, 50);
//设置路径经过的点
CGPathAddLineToPoint(path, NULL, 200, 50);
CGPathAddLineToPoint(path, NULL, 200, 250);
//将路径赋给动画对象的path
animation.path = path;
//设置动画时间
[animation setDuration:2.5];
//给_showImageView的layer层添加动画
[_showImageView.layer addAnimation:animation forKey:@"position"];
//释放路径对象
CGPathRelease(path);
}
- (IBAction)didClickCAGroupButtonAction:(id)sender {
//group动画对象
// CAAnimationGroup * group = [CAAnimationGroup animation];
CAKeyframeAnimation * animation1 = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation1.values = @[[NSValue valueWithCGPoint:CGPointMake(200, 200)],
[NSValue valueWithCGPoint:CGPointMake(80, 120)],
[NSValue valueWithCGPoint:CGPointMake(100, 300)],
[NSValue valueWithCGPoint:CGPointMake(60, 70)],
[NSValue valueWithCGPoint:CGPointMake(160, 50)]];
[_showImageView.layer addAnimation:animation1 forKey:@"position"];
CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"transform.scale.y"];
animation2.fromValue = [NSNumber numberWithFloat:1.0];
animation2.toValue = [NSNumber numberWithFloat:0.5];
[_showImageView.layer addAnimation:animation2 forKey:@"scale"];
CAAnimationGroup * group = [CAAnimationGroup animation];
[group setDuration:4.0];
group.animations = @[animation1,animation2];
[_showImageView.layer addAnimation:group forKey:@"组"];
}
- (IBAction)didClickCATransitionButtonAction:(id)sender {
CATransition * animation = [CATransition animation];
animation.duration = 1.0;
// animation.type = kCATransitionPush;
// animation.type = @"cameraIrisHollowOpen";
// 动画过渡类型
animation.type = @"cameraIrisHollowClose";
// 动画过渡方向
animation.subtype = kCATransitionFromRight;
// animation.startProgresss = 0.0;
// animation.endProgress = 0.3; //动画实现位置,
[_showImageView.layer addAnimation:animation forKey:@""];
}
地图定位
#import <UIKit/UIKit.h>
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "YellowViewController.h"
@interface RootViewController : UIViewController<MKMapViewDelegate>
@property(nonatomic,retain) MKMapView *mapView;
@property(nonatomic,retain) NSString *placrStr;
@property(nonatomic,retain) MKPinAnnotationView *annotationView;
@property(nonatomic,retain) YellowViewController *yellowVc;
@end
.mmmmmmmmmmmmmmmmmmm
#import "RootViewController.h"
#import "MyAnnotation.h"
#import "MyOverlayRenderer.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBar.hidden = YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.yellowVc = [[YellowViewController alloc] init];
// Do any additional setup after loading the view.
self.mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
[self.view addSubview:_mapView];
self.mapView.delegate = self;
//我的位置button
UIButton *abutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
abutton.frame = CGRectMake(0, 538, 60, 30);
abutton.backgroundColor = [UIColor redColor];
[abutton setTitle:@"我的位置" forState:UIControlStateNormal];
[abutton addTarget:self action:@selector(myLocation) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:abutton];
//1号位置button
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button1.frame = CGRectMake(65, 538, 60, 30);
button1.backgroundColor = [UIColor redColor];
[button1 setTitle:@"1号位置" forState:UIControlStateNormal];
[button1 addTarget:self action:@selector(one) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button1];
//2号位置
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button2.frame = CGRectMake(130, 538, 60, 30);
button2.backgroundColor = [UIColor redColor];
[button2 setTitle:@"2号位置" forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(two) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button2];
//连线的button
UIButton *button3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button3.frame = CGRectMake(200, 538, 90, 30);
button3.backgroundColor = [UIColor redColor];
[button3 setTitle:@"1和2导航" forState:UIControlStateNormal];
[button3 addTarget:self action:@selector(three) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button3];
}
- (void)three
{
CLLocationCoordinate2D fromCoordinate = CLLocationCoordinate2DMake(23.134844,113.317290);
CLLocationCoordinate2D toCoordinate = CLLocationCoordinate2DMake(23.114844,113.317290);
MKPlacemark *fromPlacemark = [[MKPlacemark alloc] initWithCoordinate:fromCoordinate addressDictionary:nil];
MKPlacemark *toPlacemark = [[MKPlacemark alloc] initWithCoordinate:toCoordinate addressDictionary:nil];
MKMapItem *fromItem = [[MKMapItem alloc] initWithPlacemark:fromPlacemark];
MKMapItem *toItem = [[MKMapItem alloc] initWithPlacemark:toPlacemark];
MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
request.source = fromItem;
request.destination = toItem;
request.requestsAlternateRoutes = YES;
MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
[directions calculateDirectionsWithCompletionHandler:
^(MKDirectionsResponse *response, NSError *error) {
if (error) {
NSLog(@"error:%@", error);
}
else {
MKRoute *route = response.routes[0];
[self.mapView addOverlay:route.polyline];
}
}];
}
//---------------------------------------------------------------------
- (void)myLocation
{
self.mapView.showsUserLocation = YES;
}
- (void)one
{
//self.mapView removeAnnotations:<#(NSArray *)#>
//设置地图中心
CLLocationCoordinate2D coordinate;
coordinate.latitude = 23.134844;
coordinate.longitude = 113.317290;
MyAnnotation *ann = [[MyAnnotation alloc] init];
ann.coordinate = coordinate;
ann.myTitle = @"吴品无品五品五品茶";
ann.mySubtitle = @"meipin";
//触发viewForAnnotation
[_mapView addAnnotation:ann];
//添加多个
//[mapView addAnnotations]
//设置显示范围
MKCoordinateRegion region;
region.span.latitudeDelta = 0.001;
region.span.longitudeDelta = 0.001;
region.center = coordinate;
// 设置显示位置(动画)
[_mapView setRegion:region animated:YES];
// 设置地图显示的类型及根据范围进行显示
[_mapView regionThatFits:region];
self.mapView.showsUserLocation = NO;
}
- (void)two
{
//解析
CLLocation *locNow = [[CLLocation alloc]initWithLatitude:23.114844 longitude:113.317290];
CLGeocoder *geocoder=[[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:locNow completionHandler:^(NSArray *placemarks,NSError *error)
{
CLPlacemark *placemark=[placemarks objectAtIndex:0];
NSLog(@"name:%@\n country:%@\n postalCode:%@\n ISOcountryCode:%@\n ocean:%@\n inlandWater:%@\n locality:%@\n subLocality:%@\n administrativeArea:%@\n subAdministrativeArea:%@\n thoroughfare:%@\n subThoroughfare:%@\n",placemark.name,placemark.country,placemark.postalCode,placemark.ISOcountryCode,placemark.ocean,placemark.inlandWater,placemark.administrativeArea,placemark.subAdministrativeArea,placemark.locality,placemark.subLocality,placemark.thoroughfare,placemark.subThoroughfare);
CLLocationCoordinate2D coordinate;
coordinate.latitude = 23.114844;
coordinate.longitude = 113.317290;
MyAnnotation *annotation = [[MyAnnotation alloc] init];
//设置中心
annotation.coordinate = coordinate;
//触发viewForAnnotation
[self.mapView addAnnotation:annotation];
//设置显示范围
MKCoordinateRegion region;
region.span.latitudeDelta = 0.001;
region.span.longitudeDelta = 0.001;
region.center = coordinate;
// 设置显示位置(动画)
[_mapView setRegion:region animated:YES];
// 设置地图显示的类型及根据范围进行显示
[_mapView regionThatFits:region];
self.mapView.showsUserLocation = NO;
annotation.myTitle =placemark.name;
//annotation.mySubtitle = [placemark.locality stringByAppendingString:placemark.subLocality];
//[placemark.locality stringByAppendingString:placemark.subAdministrativeArea];
}];
}
//当前位置location代理方法
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
CLLocationCoordinate2D loc = [userLocation coordinate];
NSLog(@"%f,%f",loc.latitude,loc.longitude);
//放大地图到自身的经纬度位置。
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 0.1, 0.1);
[self.mapView setRegion:region animated:YES];
}
- (void)mapViewDidStopLocatingUser:(MKMapView *)mapView
{
}
//map代理方法
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
//如果是当前位置,无需更改
if ([annotation isKindOfClass:[MKUserLocation class]])
{
return nil;
}
if ([annotation isKindOfClass:[MyAnnotation class]])
{
NSString *annotationViewId=@"meipinAnnotationView";
_annotationView = (MKPinAnnotationView *)
[mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewId];
if (_annotationView==nil){
//MKAnnotationView是使用自定义的图片.MKPinAnnotationView是定义系统默认的大头针
_annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewId];
_annotationView.canShowCallout = YES;
UIImageView *leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"2.png"]];
_annotationView.leftCalloutAccessoryView = leftView;
_annotationView.animatesDrop = YES;
//设置右按钮
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:nil action:nil forControlEvents:UIControlEventTouchUpInside];
_annotationView.rightCalloutAccessoryView = rightButton;
}
}
return _annotationView;
}
// user tapped the disclosure button in the callout
//
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
// here we illustrate how to detect which annotation type was clicked on for its callout
id <MKAnnotation> annotation = [view annotation];
if ([annotation isKindOfClass:[MyAnnotation class]])
{
[self.navigationController pushViewController:self.yellowVc animated:YES];
NSLog(@"123456789");
}
}
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView
rendererForOverlay:(id<MKOverlay>)overlay
{
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
renderer.lineWidth = 5.0;
renderer.strokeColor = [UIColor purpleColor];
return renderer;
}
- (void)mapView:(MKMapView *)mapView didAddOverlayRenderers:(NSArray *)renderers
{
}
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
CoreData
CoreDataManager 单例封装
@interface CoreDataManager : NSObject
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext; // 托管对象上下文
/**
* CoreDataManager 单例对象
*
* @return
*/
+ (CoreDataManager *)defaultManager;
@end
.mmmmmmmmmmmm
#import "CoreDataManager.h"
@interface CoreDataManager ()
@property (nonatomic, strong) NSPersistentStoreCoordinator *persistentStoreCoordinator; // 持久化存储协调器
@property (nonatomic, strong) NSManagedObjectModel *managedObjectModel; // 托管对象模型
@end
@implementation CoreDataManager
+ (CoreDataManager *)defaultManager
{
static CoreDataManager *manager = nil;
@synchronized(self){
if (manager == nil) {
manager = [[self alloc] init];
}
}
return manager;
}
- (NSManagedObjectContext *)managedObjectContext
{
// 如果托管对象上下文不为空的话 直接返回
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
// 不为空创建一个新的对象
_managedObjectContext = [[NSManagedObjectContext alloc] init];
// 为脱光对象上下文添加持久化存储协调器
[_managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];;
return _managedObjectContext;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// 获取我们想要创建数据库的路径
NSURL *documentURL = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].lastObject;
NSURL *fileURL = [documentURL URLByAppendingPathComponent:@"LOClass.sqlite"];
// 根据托管对象模型创建数据持久化存储协调器
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
// 数据持久化存储协调器添加存储类型和存储路径
// options参数 如果做数据库版本迁移, options必须要填写
// 字典key值含义 1: 持久化存储数据自动迁移
// 2: 自动推断数据模型映射关系
NSError *error = nil;
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:fileURL options: @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} error:&error];
if (error != nil) {
NSLog(@"%s, %d error = %@",__FUNCTION__, __LINE__, [error description]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
// 获取实体在工程包中的路径
NSURL *momdURL = [[NSBundle mainBundle] URLForResource:@"LOClassModel" withExtension:@"momd"];
// 根据可视化数据模型 创建 托管对象模型
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momdURL];
return _managedObjectModel;
}
@end
数据增删改
增:
// 创建实体描述对象
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"LOClassEntity" inManagedObjectContext:[CoreDataManager defaultManager].managedObjectContext];
// 根据实体描述对象 创建LOClass 实例对象
LOClass *loclass = [[LOClass alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:[CoreDataManager defaultManager].managedObjectContext];
[[CoreDataManager defaultManager].managedObjectContext save:nil];
删
[[CoreDataManager defaultManager].managedObjectContext deleteObject:loclass];
NSError *error = nil;
[[CoreDataManager defaultManager].managedObjectContext save:&error];
改
loclass.name = [NSString stringWithFormat:@"第%d班",arc4random()%10];
NSError *error = nil;
// 保存数据 数据持久化
[[CoreDataManager defaultManager].managedObjectContext save:&error];
查
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"LOStudentEntity"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"loclass.name = %@",self.loclass.name];
fetchRequest.predicate = predicate;
NSError *error = nil;
NSArray *loStudentArray = [[CoreDataManager defaultManager].managedObjectContext executeFetchRequest:fetchRequest error:&error];
推送
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
//五秒钟之后执行
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
//提示内容
localNotification.alertBody = @"该起床了";
//设置音效
localNotification.soundName = @"管钟琴.caf";
//设置启动图片
localNotification.alertLaunchImage = @"link_page_2";
//设置确认按钮的标题
localNotification.alertAction = @"啦啦啦";
//
localNotification.applicationIconBadgeNumber = 10;
//调用本地通知
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
常用宏定义
log输出
#define NEED_OUTPUT_LOG 0
#if NEED_OUTPUT_LOG
#define SLog(xx, ...) NSLog(xx, ##__VA_ARGS__)
#define SLLog(xx, ...) NSLog(@"%s(%d): " xx, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#define SLLogRect(rect) \
SLLog(@"%s x=%f, y=%f, w=%f, h=%f", #rect, rect.origin.x, rect.origin.y, \
rect.size.width, rect.size.height)
#define SLLogPoint(pt) \
SLLog(@"%s x=%f, y=%f", #pt, pt.x, pt.y)
#define SLLogSize(size) \
SLLog(@"%s w=%f, h=%f", #size, size.width, size.height)
#define SLLogRange(range) \
SLLog(@"%s loc=%ld, len=%ld",#range,range.location,range.length)
#define SLLogColor(_COLOR) \
SLLog(@"%s h=%f, s=%f, v=%f", #_COLOR, _COLOR.hue, _COLOR.saturation, _COLOR.value)
#define SLLogSuperViews(_VIEW) \
{ for (UIView* view = _VIEW; view; view = view.superview) { SLLog(@"%@", view); } }
#define SLLogSubViews(_VIEW) \
{ for (UIView* view in [_VIEW subviews]) { SLLog(@"%@", view); } }
#else
#define SLog(xx, ...) ((void)0)
#define SLLog(xx, ...) ((void)0)
#endif
//———————————————————————颜色类———————————————————————————-----—————————————
// rgb颜色转换(16进制->10进制)
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
//带有RGBA的颜色设置
#define COLOR(R, G, B, A) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:A]
// 获取RGB颜色
#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define RGB(r,g,b) RGBA(r,g,b,1.0f)
//背景色
#define BACKGROUND_COLOR [UIColor colorWithRed:242.0/255.0 green:236.0/255.0 blue:231.0/255.0 alpha:1.0]
//清除背景色
#define CLEARCOLOR [UIColor clearColor]
#pragma mark - color functions
#define RGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]
// 安全释放
#define RELEASE_SAFELY(__Pointer) do{[__Pointer release],__Pointer = nil;} while(0)
// 屏幕的物理高度
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
// 屏幕的物理宽度
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
// 调试
#define NSLOG_FUNCTION NSLog(@"%s,%d",__FUNCTION__,__LINE__)
系统设备
1//----------------------系统----------------------------
2
3//获取系统版本
4#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
5#define CurrentSystemVersion [[UIDevice currentDevice] systemVersion]
6
7//获取当前语言
8#define CurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])
9
10 //判断是否 Retina屏、设备是否%fhone 5、是否是iPad
11 #define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
12 #define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
13 #define isPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
14
15
16 //判断是真机还是模拟器
17 #if TARGET_OS_IPHONE
18 //iPhone Device
19 #endif
20
21 #if TARGET_IPHONE_SIMULATOR
22 //iPhone Simulator
23 #endif
24
25 //检查系统版本
26 #define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
27 #define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
28 #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
29 #define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
30 #define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
图片
31 //读取本地图片
32 #define LOADIMAGE(file,ext) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:file ofType:ext]]
33
34 //定义UIImage对象
35 #define IMAGE(A) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:A ofType:nil]]
36
37 //定义UIImage对象
38 #define ImageNamed(_pointer) [UIImage imageNamed:[UIUtil imageName:_pointer]]
39
//建议使用前两种宏定义,性能高于后者
40 //设置View的tag属性
41 #define VIEWWITHTAG(_OBJECT, _TAG) [_OBJECT viewWithTag : _TAG]
42 //程序的本地化,引用国际化的文件
43 #define MyLocal(x, ...) NSLocalizedString(x, nil)
44
45 //G-C-D
46 #define BACK(block) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
47 #define MAIN(block) dispatch_async(dispatch_get_main_queue(),block)
48
49 //NSUserDefaults 实例化
50 #define USER_DEFAULT [NSUserDefaults standardUserDefaults]
51
52
53 //由角度获取弧度 有弧度获取角度
54 #define degreesToRadian(x) (M_PI * (x) / 180.0)
55 #define radianToDegrees(radian) (radian*180.0)/(M_PI)
56
POST上传时,将汉字进行编码
//点击搜索按钮获取搜索列表url
NSString *urlString = [NSString stringWithFormat:@"%@", @"http://iphonenew.ecartoon.net/book_list.php?type=3&sub="];
IOSExcept.listTitleString = self.searchTextFiled.text;
//将文字 进行编码
// NSString *contentString = [IOSExcept.listTitleString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
/* POST 上传是汉字格式为%AE ,可以用下方法 替换 */
NSString *contentString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)
IOSExcept.listTitleString
, NULL, NULL, kCFStringEncodingUTF8);
IOSExcept.listURLString = [NSString stringWithFormat:@"%@%@",urlString,contentString];
NSLog(@"url : %@",IOSExcept.listURLString );
//重新搜
[IOSExcept.categoryListObjectArray removeAllObjects];
IOSExcept.requestData = nil;
[self.navigationController pushViewController:IOS.comicListViewController animated:YES];