首页 文章 精选 留言 我的

精选列表

搜索[ios],共10000篇文章
优秀的个人博客,低调大师

iOS_数据库3_sqlite3基本操作

终于效果图: Sqlite3函数总结 1.打开数据库 int sqlite3_open( const char *filename, // 数据库的文件路径 sqlite3 **ppDb // 数据库实例 ); 2.运行不论什么SQL语句 int sqlite3_exec( sqlite3*, // 一个打开的数据库实例 const char *sql, // 须要运行的SQL语句 int (*callback)(void*,int,char**,char**), // SQL语句运行完成后的回调 void *, // 回调函数的第1个參数 char **errmsg // 错误信息 ); 3.检查SQL语句的合法性(查询前的准备) int sqlite3_prepare_v2( sqlite3 *db, // 数据库实例 const char *zSql, // 须要检查的SQL语句 int nByte, // SQL语句的最大字节长度 sqlite3_stmt **ppStmt, // sqlite3_stmt实例,用来获得数据库数据 const char **pzTail ); 4.查询一行数据 int sqlite3_step(sqlite3_stmt*); // 假设查询到一行数据,就会返回SQLITE_ROW 5.利用stmt获得某一字段的值(字段的下标从0開始) double sqlite3_column_double(sqlite3_stmt*, int iCol); // 浮点数据 int sqlite3_column_int(sqlite3_stmt*, int iCol); // 整型数据 sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); // 长整型数据 const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); // 二进制文本数据 const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); // 字符串数据 控制器中直接写SQL语句,未封装 // // ViewController.m // 1.sqlite3基本操作 // // Created by xss on 14-11-2. // Copyright (c) 2014年 beyond. All rights reserved. // #import "ViewController.h" // 1.导入库,2.加入主头文件 #import <sqlite3.h> @interface ViewController () { // db代表着整个数据库。db是数据库实例 sqlite3 *_db; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 0.获得沙盒中的数据库文件名称 NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"student.sqlite"]; NSLog(@"filePath:%@",filename); /* 2014-11-02 18:32:38.895 1.sqlite3基本操作[85356:245858] filePath:/Users/juns/Library/Developer/CoreSimulator/Devices/3198E002-E3C9-4523-983E-AC3E1283A654/data/Containers/Data/Application/E1150608-3EB8-4B9D-87AF-33EDF9FB6FF3/Documents/student.sqlite 2014-11-02 18:32:38.896 1.sqlite3基本操作[85356:245858] 成功打开数据库 2014-11-02 18:32:38.897 1.sqlite3基本操作[85356:245858] 成功创建t_student表 */ // 1.创建(打开)数据库(假设是首次打开,则数据库文件不存在。那么会自己主动创建) // OC字符串,直接转成C语言字符串,通过 UTF8String方法 int result = sqlite3_open(filename.UTF8String, &_db); if (result == SQLITE_OK) { NSLog(@"成功打开数据库"); // 2.创表 const char *sql = "create table if not exists t_student (id integer primary key autoincrement, name text, age integer);"; // 凡是要传地址的,最好先清空,防止出现野指针,C语言中空是NULL char *errorMesg = NULL; // 參数3和4是回调时用 int result = sqlite3_exec(_db, sql, NULL, NULL, &errorMesg); if (result == SQLITE_OK) { NSLog(@"成功创建t_student表"); } else { NSLog(@"创建t_student表失败:%s", errorMesg); } } else { NSLog(@"打开数据库失败"); } } // 全然仿造createTable操作 - (IBAction)insertBtnClicked:(UIButton *)sender { for (int i = 0; i<30; i++) { NSString *name = [NSString stringWithFormat:@"beyond-%d", arc4random()%100]; int age = arc4random()%100; NSString *sql = [NSString stringWithFormat:@"insert into t_student (name, age) values('%@', %d);", name, age]; char *errorMesg = NULL; int result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &errorMesg); if (result == SQLITE_OK) { NSLog(@"成功加入数据"); } else { NSLog(@"加入数据失败:%s", errorMesg); } } } // 方法同上 - (IBAction)deleteBtnClicked:(UIButton *)sender { } // 方法同上 - (IBAction)updateBtnClicked:(UIButton *)sender { } // - (IBAction)queryBtnClicked:(UIButton *)sender { // SQL注入漏洞 /** 登录功能 1.用户输入账号和password * 账号:123' or 1 = 1 or '' = ' * password:456654679 2.拿到用户输入的账号和password去数据库查询(查询有没有这个用户名和password) select * from t_user where username = '123' and password = '456'; select * from t_user where username = '123' and password = '456'; */ // 1.定义sql语句 const char *sql = "select id, name, age from t_student where name = ?;"; // 2.定义一个stmt存放结果集,用于运行静态 SQL 语句并返回它所生成结果的对象 sqlite3_stmt *stmt = NULL; // 3.检測SQL语句的合法性,參数3是sql语句的长度,仅仅要写-1,会自己主动计算,參数4是statement存放结果集 int result = sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL); if (result == SQLITE_OK) { NSLog(@"查询语句是合法的"); // 设置占位符的内容,參数2 指的是第几个占位符号,注意是从1開始;參数4是占位符的长度,仅仅要写-1,会自己主动计算, sqlite3_bind_text(stmt, 1, "beyond", -1, NULL); // 4.step 运行SQL语句,从结果集中取出数据 // int stepResult = sqlite3_step(stmt); // step的运行结果等于SQLITE_ROW,表示真的查询到一行数据 while (sqlite3_step(stmt) == SQLITE_ROW) { // 获得这行相应的数据,结果存放在statement中 // 获得第0列的id int sid = sqlite3_column_int(stmt, 0); // 获得第1列的name const unsigned char *sname = sqlite3_column_text(stmt, 1); // 获得第2列的age int sage = sqlite3_column_int(stmt, 2); NSLog(@"%d %s %d", sid, sname, sage); } } else { NSLog(@"查询语句非合法"); } } @end 使用工具类封装 模型 // // Student.h // 2_数据库工具类封装 // // Created by xss on 14-11-2. // Copyright (c) 2014年 beyond. All rights reserved. // #import <Foundation/Foundation.h> @interface Student : NSObject // 学号 @property (nonatomic, assign) int ID; // 姓名 @property (nonatomic, copy) NSString *name; // 年龄 @property (nonatomic, assign) int age; @end 工具类StudentDAO // // StudentDAO.h // 2_数据库工具类封装 // // Created by xss on 14-11-2. // Copyright (c) 2014年 beyond. All rights reserved. // 学生数据的CRUD(增删改查) #import <Foundation/Foundation.h> @class Student; @interface StudentDAO : NSObject /** * 加入学生 * * @param student 须要加入的学生 */ + (BOOL)addStudent:(Student *)student; /** * 获得全部的学生 * * @return 数组中装着都是IWStudent模型 */ + (NSArray *)students; /** * 依据搜索条件获得相应的学生 * * @param condition 搜索条件 */ + (NSArray *)studentsWithCondition:(NSString *)condition; @end 关键封装的代码 // // StudentDAO.m // 2_数据库工具类封装 // // Created by xss on 14-11-2. // Copyright (c) 2014年 beyond. All rights reserved. // #import "StudentDAO.h" #import "Student.h" #import <sqlite3.h> @implementation StudentDAO // 重点~~~~加上static的作用:能保证_db这个变量仅仅被StudentDAO.m内部訪问 static sqlite3 *_db; // 重点~~~~工具类第一次载入的时候调用initialize方法 + (void)initialize { // 0.获得沙盒中的数据库文件名称 NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"student.sqlite"]; // 1.创建(打开)数据库(假设数据库文件不存在。会自己主动创建) int result = sqlite3_open(filename.UTF8String, &_db); if (result == SQLITE_OK) { NSLog(@"成功打开数据库"); // 2.创表 const char *sql = "create table if not exists t_student (id integer primary key autoincrement, name text, age integer);"; char *errorMesg = NULL; int result = sqlite3_exec(_db, sql, NULL, NULL, &errorMesg); if (result == SQLITE_OK) { NSLog(@"成功创建t_student表"); } else { NSLog(@"创建t_student表失败:%s", errorMesg); } } else { NSLog(@"打开数据库失败"); } for (int i = 0; i<30; i++) { NSString *name = [NSString stringWithFormat:@"beyond-%d", arc4random()%100]; int age = arc4random()%100; NSString *sql = [NSString stringWithFormat:@"insert into t_student (name, age) values('%@', %d);", name, age]; char *errorMesg = NULL; int result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &errorMesg); if (result == SQLITE_OK) { NSLog(@"成功加入数据"); } else { NSLog(@"加入数据失败:%s", errorMesg); } } } + (BOOL)addStudent:(Student *)student { // Sqlite3中全部的字符串必须用单引號 NSString *sql = [NSString stringWithFormat:@"insert into t_student (name, age) values('%@', %d);", student.name, student.age]; char *errorMesg = NULL; // 两个NULL代表的是回调方法,此处不须要 int result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &errorMesg); return result == SQLITE_OK; } // 返回全部的学生对象组成的数组 + (NSArray *)students { // 0.定义数组 NSMutableArray *students = nil; // 1.定义sql语句 const char *sql = "select id, name, age from t_student;"; // 2.定义一个stmt存放结果集 sqlite3_stmt *stmt = NULL; // 3.检測SQL语句的合法性 int result = sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL); if (result == SQLITE_OK) { NSLog(@"查询语句是合法的"); students = [NSMutableArray array]; // 4.运行SQL语句,从结果集中取出数据 while (sqlite3_step(stmt) == SQLITE_ROW) { // 真的查询到一行数据 // 获得这行相应的数据 Student *student = [[Student alloc] init]; // 获得第0列的id student.ID = sqlite3_column_int(stmt, 0); // 获得第1列的name const unsigned char *sname = sqlite3_column_text(stmt, 1); student.name = [NSString stringWithUTF8String:(const char *)sname]; // 获得第2列的age student.age = sqlite3_column_int(stmt, 2); // 加入到数组 [students addObject:student]; } } else { NSLog(@"查询语句非合法"); } return students; } // 模糊查询 + (NSArray *)studentsWithCondition:(NSString *)condition { // 0.定义数组 NSMutableArray *students = nil; // 1.定义sql语句 带模糊查询 '%林%' const char *sql = "select id, name, age from t_student where name like ? ;"; // 2.定义一个stmt存放结果集 sqlite3_stmt *stmt = NULL; // 3.检測SQL语句的合法性 int result = sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL); if (result == SQLITE_OK) { NSLog(@"查询语句是合法的"); students = [NSMutableArray array]; // 填补占位符的内容,%在OC中是keyword,因此转义 NSString *newCondition = [NSString stringWithFormat:@"%%%@%%", condition]; sqlite3_bind_text(stmt, 1, newCondition.UTF8String, -1, NULL); // 4.运行SQL语句,从结果集中取出数据 while (sqlite3_step(stmt) == SQLITE_ROW) { // 真的查询到一行数据 // 获得这行相应的数据 Student *student = [[Student alloc] init]; // 获得第0列的id student.ID = sqlite3_column_int(stmt, 0); // 获得第1列的name const unsigned char *sname = sqlite3_column_text(stmt, 1); student.name = [NSString stringWithUTF8String:(const char *)sname]; // 获得第2列的age student.age = sqlite3_column_int(stmt, 2); // 加入到数组 [students addObject:student]; } } else { NSLog(@"查询语句非法"); } return students; } @end 控制器中使用工具类为tableView提供数据源,而且监听搜索框的模糊查询 // // ViewController.m // 2_数据库工具类封装 // // Created by xss on 14-11-2. // Copyright (c) 2014年 beyond. All rights reserved. // #import "ViewController.h" #import "Student.h" #import "StudentDAO.h" @interface ViewController ()<UISearchBarDelegate> // 从数据库中返回的封装好的对象数组,为tableView提供数据源 @property (nonatomic, strong) NSArray *students; @end @implementation ViewController #pragma mark - 懒载入 - (NSArray *)students { if (_students == nil) { _students = [StudentDAO students]; } return _students; } - (void)viewDidLoad { [super viewDidLoad]; // 加入一个搜索框,并设置代理 UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; searchBar.delegate = self; // headView self.tableView.tableHeaderView = searchBar; } #pragma mark - 搜索框代理 - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { // 直接覆盖原来的对象数组 self.students = [StudentDAO studentsWithCondition:searchText]; // 刷新表格 [self.tableView reloadData]; } #pragma mark - tableView代理方法 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.students.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // 1.创建cell static NSString *ID = @"student"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID]; } // 2.设置cell的数据 Student *stu = self.students[indexPath.row]; cell.textLabel.text = stu.name; cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", stu.age]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self.view endEditing:YES]; } @end 版权声明:本文博主原创文章,博客,未经同意不得转载。 本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/4865134.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

IOS的消息传递机制,使用NSNotificationCenter进行通信,很实用

概述 在这个文档中,我们将讨论2个不相关的或者彼此之间不知道对方id的对象是如何通信的.所有的例子都是基于Objective-C的,这篇文章的关注点是Iphone开发.这个手册对那些在iphone开发和想要提高软件的易用性,扩展性的人将非常有用. 下面,我们将讨论具体的项目细节(http://www.hivestudio.cat/goldCube.zip),这个例子是一个小的OpenGL视图程序,你可以对金色正方体进行翻转.图片 使用者可以用"Rotate X""Rotate Y"和"Rotate Z"进行操作. 当使用者点击"Rotate X"按钮,"ViewController"中的“button1()”函数将被调用.然后"ViewController"将通知“OpenGLView”,告诉他,用户要进行翻转物体,问题是“ViewController”并没有任何"OpenGLView"实例,唯一可行的方法是使用"NotificationCenter"进行通信. 下面是使用“NotificationCenter”对"ViewController"和"OpenGLView"进行通信的步骤: 1) 在OpenGLView中添加消息的观察者. OpenGLView.m - (void)prepareOpenGL { //1 -> Adding OpenGLView as an observer.[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(RotateX)name:@"button1"//表示消息名称,发送跟接收双方都要一致object:nil]... } 2)在"ViewController"中发送消息. viewController.m - (IBAction)button1:(id)pId; { //3 -> SENDING THE MESSAGE[[NSNotificationCenter defaultCenter] postNotificationName:@"button1" object:self];//注意object属性 } 3)"OpenGLView"相应对此消息的对应方法. OpenGLView.m //2 à IMPLEMENTING THE METHOD - (void) RotateX { NSLog(@"rotateX"); dAnlgeX=dAnlgeX+10; } 这些步骤允许我们在"OpenGLView"和"viewController"之间传递消息 同时在dealloc方法,将observer从notification center中移除 - (void)dealloc { [self setEmployees:nil]; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc removeObserver:self]; [super dealloc]; } 本文转自编程小翁博客园博客,原文链接:http://www.cnblogs.com/wengzilin/archive/2012/03/15/2398229.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

[cocos2d-x]SpaceFighting[安卓/IOS都适用]

前言:闲来无事找个小游戏项目练练手吧!也供初学者朋友学习和参考,让我们共同进步!下面我就介绍一下一个类似打飞机游戏的小项目的制作,实现跟微信打飞机一样的效果!并且成功导入到安卓机上! 项目设计大概思路: 1.游戏的菜单界面的编写(Play、Score、About) 添加背景音乐->选项场景的创建->设置关闭声音->游戏测试 2.游戏舞台屏幕的编写,背景无限移动 3.飞船类的编写 4.敌机的编写 5.子弹类以及碰撞检测的编写 6.游戏胜利以及失败场景的编写 详细设计: 1.主场景(菜单选项场景)的设计 HMenu.h: // // HMenu.h // dafeiji // // Created by 丁小未 on 13-9-25. // // #ifndef __dafeiji__HMenu__ #define __dafeiji__HMenu__ #include <iostream> #include "cocos2d.h" using namespace cocos2d; class HMenu : public CCLayer { public: virtual bool init(); static CCScene * scene(); CREATE_FUNC(HMenu); private: //开始游戏 void playerIsPressed(); //分数显示 void scoreIsPressed(); //关于作者 void aboutIsPressed(); }; #endif /* defined(__dafeiji__HMenu__) */ HMenu.cpp: // // HMenu.cpp // dafeiji // // Created by 丁小未 on 13-9-25. // // #include "HMenu.h" #include "SimpleAudioEngine.h" #include "HScore.h" #include "HAbout.h" #include "HWorld.h" using namespace cocos2d; using namespace CocosDenshion; CCScene * HMenu::scene() { CCScene *scene = CCScene::create(); HMenu * layer = HMenu::create(); scene->addChild(layer); return scene; } bool HMenu::init() { if (!CCLayer::init()) { return false; } SimpleAudioEngine::sharedEngine()->playBackgroundMusic("menuMusic", true); CCSize size = CCDirector::sharedDirector()->getWinSize(); //添加背景精灵 CCSprite *sp = CCSprite::create("menu_bg.png"); sp->setPosition(CCPointMake(size.width/2, size.height/2)); addChild(sp); //添加三个菜单选项贴图 CCMenuItemImage *itemPlay = CCMenuItemImage::create("play_nor.png", "play_pre.png",this,menu_selector(HMenu::playerIsPressed)); CCMenuItemImage * itemScore = CCMenuItemImage::create("score_nor.png", "score_pre.png", this, menu_selector(HMenu::scoreIsPressed)); itemScore->setPosition(CCPointMake(0, -itemScore->getContentSize().height - 20)); CCMenuItemImage * itemAbout = CCMenuItemImage::create("about_nor.png", "about_pre.png",this,menu_selector(HMenu::aboutIsPressed)); itemAbout->setPosition(CCPointMake(0, -itemAbout->getContentSize().height*2 - 40)); //添加菜单选项卡 CCMenu *menu = CCMenu::create(itemPlay,itemScore,itemAbout,NULL); addChild(menu); return true; } //进入玩游戏主场景 void HMenu::playerIsPressed() { CCLog("1"); CCDirector::sharedDirector()->replaceScene(CCTransitionFadeDown::create(1, HWorld::scene())); } //进入显示分数场景 void HMenu::scoreIsPressed() { CCLog("2"); CCDirector::sharedDirector()->replaceScene(CCTransitionCrossFade::create(1, HScore::scene())); } //进入关于作者场景 void HMenu::aboutIsPressed() { CCLog("3"); CCDirector::sharedDirector()->replaceScene(CCTransitionCrossFade::create(1, HAbout::scene())); } 2.游戏背景的设计(实现无限滚屏,也就是两张图片来回不停切换) HMap.h: // // HMap.h // dafeiji // // Created by 丁小未 on 13-9-26. // // #ifndef __dafeiji__HMap__ #define __dafeiji__HMap__ #include <iostream> #include "cocos2d.h" using namespace cocos2d; typedef enum { tag_oneImg, tag_twoImg, }tagMap; class HMap:public CCLayer { public: //创建一个map static HMap* createMap(const char * fileName); private: void mapInit(const char * fileName); void update(float time); virtual void onExit(); }; #endif /* defined(__dafeiji__HMap__) */ HMap.cpp: // // HMap.cpp // dafeiji // // Created by 丁小未 on 13-9-26. // // #include "HMap.h" //模仿CREATE_FUNC()函数自己创建一个对象 HMap * HMap::createMap(const char *fileName) { HMap * map = new HMap(); if (map&&map->create()) { map->autorelease(); map->mapInit(fileName); return map; } CC_SAFE_DELETE(map); return NULL; } void HMap::mapInit(const char *fileName) { CCSize size = CCDirector::sharedDirector()->getWinSize(); //创建两张图片精灵来回切换 CCSprite * turnImg1 = CCSprite::create(fileName); turnImg1->setPosition(CCPointMake(turnImg1->getContentSize().width/2, turnImg1->getContentSize().height/2)); this->addChild(turnImg1,0,tag_oneImg); CCSprite * turnImg2 = CCSprite::create(fileName); turnImg2->setPosition(CCPointMake(turnImg2->getContentSize().width/2, turnImg2->getContentSize().height * 1.5)); this->addChild(turnImg2,0,tag_twoImg); //启动定时器来实现两张背景图片的循环交叉滚动 this->scheduleUpdate(); } //自上而下滚屏效果 void HMap::update(float time) { CCSize size = CCDirector::sharedDirector()->getWinSize(); CCSprite * sp1 = (CCSprite *)this->getChildByTag(tag_oneImg); //如果第一张背景图的中点到达屏幕下方背景图高度的一半的时候(也就是第一张图片移除图片下面的时候)重新设置他的位置到屏幕上面,图片下边缘跟手机屏幕上边缘重合-1个像素 if (sp1->getPositionY()<=-sp1->getContentSize().height/2) { sp1->setPosition(CCPointMake(sp1->getContentSize().width/2, sp1->getContentSize().height*1.5f - 1)); } //如果还没需要换位置就让他向下移动一个像素 else { sp1->setPosition(ccpAdd(sp1->getPosition(), ccp(0,-1))); } CCSprite * sp2 = (CCSprite *)this->getChildByTag(tag_twoImg); //如果第二张背景图移出屏幕最下方则重新设置他的位置在屏幕的最上方 if (sp2->getPositionY()<=-sp2->getContentSize().height/2) { sp2->setPosition(CCPointMake(sp2->getContentSize().width/2, sp2->getContentSize().height*1.5 - 1)); } //向下移动 else{ sp2->setPosition(ccpAdd(sp2->getPosition(), ccp(0,-1))); } } //如果退出 void HMap::onExit() { this->unscheduleUpdate(); CCLayer::onExit();//还要调用父类的退出方法 } 3.主角类的设计: HPlayer.h: // // HPlayer.h // dafeiji // // Created by 丁小未 on 13-9-26. // // #ifndef __dafeiji__HPlayer__ #define __dafeiji__HPlayer__ #include <iostream> #include "cocos2d.h" #include <sstream> using namespace std; //导入C++命名空间 using namespace cocos2d; //模板,将任意类型转化成string类型 template <typename T> string Convert2String(const T &value) { stringstream ss; ss<<value; return ss.str(); } //创建player,具备点击的精灵 class HPlayer: public CCSprite,public CCTouchDelegate { public: //创建主角精灵 static HPlayer * createPlayer(const char* fileName); //当前血量 int hp; //最大血量 int hpMax; //分数 int score; //杀敌数 int killCount; //掉血 void downHp(); //添加分数 void addScore(float _value); //添加杀敌数 void addKillCount(float _value); //判断是否死亡 bool isDead; //private: //无敌状态的时间 int strongTime; //是否无敌状态 bool isStrong; // int strongCount; //无敌状态函数 void strongIng(); //主角精灵初始化 void playerInit(); virtual void onEnter(); virtual void onExit(); virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); }; #endif /* defined(__dafeiji__HPlayer__) */ HPlayer.cpp: // // HPlayer.cpp // dafeiji // // Created by 丁小未 on 13-9-26. // // #include "HPlayer.h" #include "HWorld.h" using namespace cocos2d; //创建主角精灵 HPlayer *HPlayer::createPlayer(const char* fileName) { HPlayer * player=new HPlayer(); //由于继承自CCSprite,然后调用CCSprite的initWithFile方法 if (player && player->initWithFile(fileName)) { player->autorelease(); //调用初始化方法 player->playerInit(); return player; } CC_SAFE_DELETE(player); return NULL; } //设置配置参数,初始化血量,杀敌数等 void HPlayer::playerInit() { CCSize size=CCDirector::sharedDirector()->getWinSize(); //设置主角的位置在屏幕下面正中央 this->setPosition(ccp(size.width*0.5, this->getContentSize().height*0.5)); //设置参数(血量,当前血量,无敌时间,分数) hpMax=5; hp=5; score=0; strongTime=2*60; //添加右下角的血量贴图 for (int i=0; i<5; i++) { CCSprite *spHp=CCSprite::create("icon_hp.png"); //设置每个血量贴图在屏幕的右下角一次排列,并且从右至左tag分别是值为5,4,3,2,1的枚举类型 spHp->setPosition(ccp(size.width-this->getContentSize().width*0.5*i-20, spHp->getContentSize().height*0.5)); if (i==0) { spHp->setTag(tag_playerHP1); }else if(i==1){ spHp->setTag(tag_playerHP2); }else if(i==2){ spHp->setTag(tag_playerHP3); }else if(i==3){ spHp->setTag(tag_playerHP4); }else if(i==4){ spHp->setTag(tag_playerHP5); } //将每一个血量贴图添加到HWorld场景中 HWorld::sharedWorld()->addChild(spHp,10); } //添加分数label CCLabelTTF *label=CCLabelTTF::create("分数", "Helvetica-Blood", 24); label->setPosition(ccp(30, size.height-22)); //位置左上方 HWorld::sharedWorld()->addChild(label,10); //分数结果 string strScore=Convert2String(score); CCLabelTTF * labelScores=CCLabelTTF::create(strScore.c_str(),"Helvetica-Blood",24); labelScores->setPosition(ccp(110, size.height-22)); labelScores->setColor(ccc3(255, 255, 0)); //设置颜色为黄色 HWorld::sharedWorld()->addChild(labelScores,10,tag_scoreTTF); //添加杀敌label CCLabelTTF *labelKill=CCLabelTTF::create("杀敌", "Helvetica-Blood", 24); labelKill->setPosition(ccp(30, size.height-52)); HWorld::sharedWorld()->addChild(labelKill,10); //杀敌数 string strKillCount=Convert2String(killCount); strKillCount+="/100"; //C++中string可以直接拼接 CCLabelTTF *labelKillCount=CCLabelTTF::create(strKillCount.c_str(), "Helvetica-Blood", 24); labelKillCount->setPosition(ccp(110, size.height-52)); labelKillCount->setColor(ccc3(255, 255, 0)); //设置为黄色 HWorld::sharedWorld()->addChild(labelKillCount,10,tag_killsCountTTF); } //添加分数 void HPlayer::addScore(float _value) { score+=_value; string strScore=Convert2String(score); //根据HWorld获取场景中分数标签并且改变他的值 CCLabelTTF *ttf=(CCLabelTTF *)HWorld::sharedWorld()->getChildByTag(tag_scoreTTF); ttf->setString(strScore.c_str()); } //添加杀敌数 void HPlayer::addKillCount(float _value) { killCount+=_value; string strKillCount=Convert2String(killCount); strKillCount+="/100"; //获取HWorld中杀敌数标签,并且改变他的值 CCLabelTTF *ttf=(CCLabelTTF *)HWorld::sharedWorld()->getChildByTag(tag_killsCountTTF); ttf->setString(strKillCount.c_str()); //当杀敌过百的时候,游戏胜利 if (killCount>=100) { // int oldScore=atoi(CCUserDefault::sharedUserDefault()->getStringForKey("user_score","-1").c_str());//当取出的键值为NULL的时候默认为1 if (oldScore!=-1&&score>oldScore) { CCUserDefault::sharedUserDefault()->setStringForKey("user_score", Convert2String(score)); CCUserDefault::sharedUserDefault()->flush(); //必须要写,刷新数据 } //调用胜利界面 HWorld::sharedWorld()->winGame(); } } //让主角掉血的方法,分为死亡和飞死亡两种情况来分析 void HPlayer::downHp() { //如果还出于无敌状态则不需要掉血 if (isStrong) { return; } //血量减少1 hp-=1; //如果血量少于0,则将主角设置不可见并且设置他已经死亡 if (hp<=0) { this->setVisible(false); isDead=true; //取出旧的分数 int oldScore=atoi(CCUserDefault::sharedUserDefault()->getStringForKey("user_score","-1").c_str()); //当有新的分数,就将新的分数保存到数据中,并且要刷新保存 if (oldScore!=-1&&score>oldScore) { CCUserDefault::sharedUserDefault()->setStringForKey("user_score", Convert2String(score)); CCUserDefault::sharedUserDefault()->flush(); } HWorld::sharedWorld()->lostGame(); } //如果主角还为死亡然后移除相应界面中的血量贴图 else { switch (hp) { case 1: HWorld::sharedWorld()->removeChildByTag(tag_playerHP2, true); break; case 2: HWorld::sharedWorld()->removeChildByTag(tag_playerHP3, true); break; case 3: HWorld::sharedWorld()->removeChildByTag(tag_playerHP4, true); break; case 4: HWorld::sharedWorld()->removeChildByTag(tag_playerHP5, true); break; } //将无敌状态开启,并且开启无敌状态的定时器 isStrong=true; strongCount=0;//无敌状态的时间 this->schedule(schedule_selector(HPlayer::strongIng)); } } //正处于无敌状态中 void HPlayer::strongIng() { strongCount++; //当无敌状态时间到的时候,取消无敌状态,并设置为可见,并且取消定时器 if (strongCount%strongTime==0) { this->setVisible(true); isStrong=false; this->unschedule(schedule_selector(HPlayer::strongIng)); } else //如果是无敌状态,让他不断的闪烁 { if (strongCount%3==0) { this->setVisible(false); }else{ this->setVisible(true); } } } //当主角精灵初始化的时候注册他的触摸事件 void HPlayer::onEnter() { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true); CCSprite::onEnter(); //调用父类的onEnter方法,这里是调用的CCNode的onEnter方法 } //当主角精灵退出的时候取消他的注册触摸事件 void HPlayer::onExit() { CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this); CCSprite::onExit(); } //设置主角精灵的当前位置 bool HPlayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { this->setPosition(pTouch->getLocation()); return true; } //触摸移动的时候不断的去移动主角精灵让他跟随着鼠标移动而移动 void HPlayer::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) { this->setPosition(pTouch->getLocation()); } //触摸结束 void HPlayer::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) { this->setPosition(pTouch->getLocation()); } 4.敌人类的设计: HEnemy.h: // // HEenemy.h // dafeiji // // Created by 丁小未 on 13-9-26. // // #ifndef __dafeiji__HEenemy__ #define __dafeiji__HEenemy__ #include <iostream> #include "cocos2d.h" using namespace cocos2d; class HEnemy:public CCSprite { public: //创建Enemy static HEnemy* createEnemy(const char *fileName,int _type); //怪物的值 int scoreValue; private: void enemyInit(const char * fileName,int _type); void createAnimate(const char *fileName,int allCount); void update(float time); //是否被攻击了 bool isActed; int type; }; #endif /* defined(__dafeiji__HEenemy__) */ HEnemy.cpp: // // HEenemy.cpp // dafeiji // // Created by 丁小未 on 13-9-26. // // #include "HEenemy.h" #include "HWorld.h" using namespace cocos2d; //创建Enemy HEnemy* HEnemy::createEnemy(const char *fileName, int _type) { HEnemy * enemy = new HEnemy(); if (enemy && enemy->initWithFile(fileName)) { enemy->autorelease(); enemy->enemyInit(fileName, _type); return enemy; } CC_SAFE_DELETE(enemy); return NULL; } void HEnemy::enemyInit(const char *fileName, int _type) { type = _type; createAnimate(fileName, 10);//创建动画 CCSize size = CCDirector::sharedDirector()->getWinSize(); if (_type == 0) { scoreValue = 198; } else if(_type == 1) { scoreValue = 428; } else if(_type == 2) { scoreValue = 908; } this->setPosition(CCPointMake(CCRANDOM_0_1()*size.width, size.height+this->getContentSize().height)); this->scheduleUpdate(); } void HEnemy::update(float time) { switch (type) { case 0: { this->setPosition(ccpAdd(this->getPosition(), ccp(0,-3))); break; } case 1: { if (isActed) { break; } isActed = true; this->runAction(CCSequence::create(CCMoveTo::create(1.6, HWorld::sharedWorld()->getPlayer()->getPosition()),CCDelayTime::create(1.0),CCMoveTo::create(1.8, this->getPosition()),NULL)); break; } } if (this->getPositionY()<-this->getContentSize().height) { HWorld::sharedWorld()->getArrayForEnemy()->removeObject(this); this->getParent()->removeChild(this,true); } HPlayer * player = HWorld::sharedWorld()->getPlayer(); if (!player->isDead) { if (player->boundingBox().intersectsRect(this->boundingBox())) { player->downHp(); } } } //创建动画 void HEnemy::createAnimate(const char *fileName, int allCount) { CCAnimation *animation = CCAnimation::create(); CCTexture2D *texture = CCTextureCache::sharedTextureCache()->addImage(fileName); int eachWith = this->getContentSize().width/allCount; for (int i = 0; i<allCount; i++) { animation->addSpriteFrameWithTexture(texture, CCRectMake(i*eachWith, 0, eachWith, this->getContentSize().height)); } animation->setDelayPerUnit(0.03f); animation->setRestoreOriginalFrame(true); animation->setLoops(-1); CCFiniteTimeAction *animate = CCAnimate::create(animation); this->runAction(animate); } 5.子弹类的设计: HBullet.h: // // HBullet.h // dafeiji // // Created by 丁小未 on 13-9-26. // // #ifndef __dafeiji__HBullet__ #define __dafeiji__HBullet__ #include <iostream> #include "cocos2d.h" using namespace cocos2d; class HBullet:public CCSprite { public: //创建子弹 static HBullet * createBullet(const char *_fileName,float _speed,CCPoint _position); private: //子弹的初始化,供create调用 void bulletInit(float _speed,CCPoint _position); void update(float time); float speed; virtual void onExit(); }; #endif /* defined(__dafeiji__HBullet__) */ HBullet.cpp: // // HBullet.cpp // dafeiji // // Created by 丁小未 on 13-9-26. // // #include "HBullet.h" #include "HWorld.h" #include "HEenemy.h" #include "SimpleAudioEngine.h" using namespace CocosDenshion; HBullet *HBullet::createBullet(const char *_fileName,float _speed, CCPoint _position) { HBullet *bullet=new HBullet(); if (bullet && bullet->initWithFile(_fileName)) { bullet->autorelease(); bullet->bulletInit(_speed, _position); return bullet; } CC_SAFE_DELETE(bullet); return NULL; } //初始化子弹的速度以及位置,并且调用子弹的update方法 void HBullet::bulletInit(float _speed,CCPoint _position) { speed=_speed; this->setPosition(_position); this->scheduleUpdate(); } //碰撞检测 void HBullet::update(float time) { //不断的改变子弹的位置(当前坐标+子弹的速度) this->setPosition(ccpAdd(this->getPosition(),ccp(0, speed))); //获取敌人对象数组 CCArray *array=HWorld::sharedWorld()->getArrayForEnemy(); //依次的遍历敌人进行碰撞检测 for (int i=0; i<array->count(); i++) { //获取一个敌人对象 HEnemy *enemy=(HEnemy *)array->objectAtIndex(i); //如果两个有碰撞 if (enemy->boundingBox().intersectsRect(this->boundingBox())) { //调用击中音效 SimpleAudioEngine::sharedEngine()->playEffect("effect_boom.mp3"); //播放击中的爆破效果 CCParticleSystemQuad *particle=CCParticleSystemQuad::create("particle_boom.plist"); particle->setPosition(enemy->getPosition()); //将爆破效果执行结束后移除 particle->setAutoRemoveOnFinish(true); //将爆破效果添加到主场景中 HWorld::sharedWorld()->addChild(particle); //调用主场景中获取主角的方法并调用他的addScore方法 HWorld::sharedWorld()->getPlayer()->addScore(enemy->scoreValue); HWorld::sharedWorld()->getPlayer()->addKillCount(1); //从数组中移除到当前的敌人 array->removeObject(enemy); //从界面中移除敌人 HWorld::sharedWorld()->removeChild(enemy, true); //移除当前的子弹类 HWorld::sharedWorld()->removeChild(this, true); } } } //退出的时候将子弹的Update方法取消 void HBullet::onExit() { this->unscheduleUpdate(); //注意要调用父类的退出方法 CCSprite::onExit(); } 6.游戏Fighting主场景的设计 HWorld.h: // // HWorld.h // dafeiji // // Created by 丁小未 on 13-9-26. // // #ifndef __dafeiji__HWorld__ #define __dafeiji__HWorld__ #include <iostream> #include "cocos2d.h" #include "HPlayer.h" typedef enum { //主角的tag tag_player, //5个血量的tag tag_playerHP1, tag_playerHP2, tag_playerHP3, tag_playerHP4, tag_playerHP5, //分数的Label的tag tag_scoreTTF, //杀敌数的tag tag_killsCountTTF, }tagWorld; using namespace cocos2d; class HWorld : public CCLayer{ public: static CCScene * scene(); static HWorld * sharedWorld(); //获取玩家精灵 HPlayer *getPlayer(); //获取敌人数组 CCArray *getArrayForEnemy(); void lostGame(); void winGame(); private: virtual bool init(); CREATE_FUNC(HWorld); virtual ~HWorld(); HWorld(); void backMenu();//返回菜单 CCArray *arrayEnemy; void autoCreateEnemy(); void autoCreateBullet(); }; #endif /* defined(__dafeiji__HWorld__) */ HWorld.cpp: // // HWorld.cpp // dafeiji // // Created by 丁小未 on 13-9-26. // // #include "HWorld.h" #include "SimpleAudioEngine.h" #include "HMap.h" #include "HPlayer.h" #include "HMenu.h" #include "HBullet.h" #include "HEenemy.h" using namespace CocosDenshion; static HWorld *sh ; HWorld* HWorld::sharedWorld() { if (sh!= NULL) { return sh; } return NULL; } CCScene * HWorld::scene() { CCScene * scene = CCScene::create(); HWorld * layer = HWorld::create(); scene->addChild(layer); return scene; } bool HWorld::init() { if (!CCLayer::init()) { return false; } //获取到当前的对象 sh = this; //播放场景音乐 SimpleAudioEngine::sharedEngine()->playBackgroundMusic("gameMusic.mp3", true); //添加背景 HMap * map = HMap::createMap("map.png"); addChild(map); //添加主角精灵 HPlayer * player = HPlayer::createPlayer("player.png"); addChild(player,0,tag_player); //创建子弹 this->schedule(schedule_selector(HWorld::autoCreateBullet),0.3); //创建敌人 this->schedule(schedule_selector(HWorld::autoCreateEnemy),1); //创建arrayEnemy arrayEnemy = CCArray::create(); CC_SAFE_RETAIN(arrayEnemy); return true; } //自动创建不同的敌人 void HWorld::autoCreateEnemy() { int randomCount=CCRANDOM_0_1()*10; for (int i=0; i<randomCount; i++) { int random=CCRANDOM_0_1()*10; HEnemy *enemy=NULL; int randomType=CCRANDOM_0_1()*10; const char *name; if (random>=0&&random<=2) { name="enemy_bug.png"; }else if(random>=3&&random<=6) { name="enemy_duck.png"; }else if(random>=7&&random<=10) { name="enemy_pig.png"; } if (randomType%2==0) { randomType=0; }else { randomType=1; } enemy=HEnemy::createEnemy(name, randomType); arrayEnemy->addObject(enemy); addChild(enemy); } } //自动创建子弹 void HWorld::autoCreateBullet() { HPlayer *player=(HPlayer *)this->getChildByTag(tag_player); this->addChild(HBullet::createBullet("p_bullet.png", 1, ccpAdd(player->getPosition(), ccp(0, player->getContentSize().height*0.5)))); SimpleAudioEngine::sharedEngine()->playEffect("effect_bullet.mp3"); } //游戏胜利场景 void HWorld::winGame() { CCSize size = CCDirector::sharedDirector()->getWinSize(); //创建一个带有颜色的层 CCLayerColor *layer = CCLayerColor::create(ccc4(0, 0, 0, 190),size.width,size.height); //创建背景图片 CCSprite * sp = CCSprite::create("game_win.png"); sp->setPosition(CCPointMake(size.width/2, size.height/2)); layer->addChild(sp); addChild(layer,100); //添加菜单项 CCLabelTTF * ttback = CCLabelTTF::create("返回主菜单", "Helvetica-Bold", 23); CCMenuItemLabel *menuLabel = CCMenuItemLabel::create(ttback, this, menu_selector(HWorld::backMenu)); menuLabel->setPosition(CCPointMake(0, -200)); CCMenu * menu = CCMenu::create(menuLabel,NULL); addChild(menu,100); //游戏暂停 CCDirector::sharedDirector()->pause(); } //游戏失败场景 void HWorld::lostGame() { CCSize size = CCDirector::sharedDirector()->getWinSize(); //创建有色层 CCLayerColor * layer = CCLayerColor::create(ccc4(0, 0, 0, 190), size.width, size.height); CCSprite *sp = CCSprite::create("game_lost.png"); sp->setPosition(CCPointMake(size.width/2, size.height/2)); //将图片添加到层中 layer->addChild(sp); //将层添加到场景中 this->addChild(layer,100); CCLabelTTF *ttback = CCLabelTTF::create("返回主菜单", "Helvetica-Bold", 23); CCMenuItemLabel *menuLabel = CCMenuItemLabel::create(ttback, this, menu_selector(HWorld::backMenu)); //菜单选项卡在CCMenu中的坐标系是以屏幕的中点为原点 menuLabel->setPosition(CCPointMake(0, -200)); CCMenu* menu = CCMenu::create(menuLabel,NULL); addChild(menu,100); CCDirector::sharedDirector()->pause(); } //通过tag获取主角精灵 HPlayer * HWorld::getPlayer() { HPlayer * player=(HPlayer *)HWorld::sharedWorld()->getChildByTag(tag_player); return player; } //返回敌人数组 CCArray * HWorld::getArrayForEnemy() { return arrayEnemy; } //返回菜单 void HWorld::backMenu() { this->unscheduleAllSelectors(); CCDirector::sharedDirector()->resume(); CCDirector::sharedDirector()->replaceScene(HMenu::scene()); } //构造函数 HWorld::HWorld(){} //析构函数 HWorld::~HWorld() { //清除敌人数组 } 7.分数场景的设计: HScore.h: // // HScore.h // dafeiji // // Created by 丁小未 on 13-9-25. // // #ifndef __dafeiji__HScore__ #define __dafeiji__HScore__ #include <iostream> #include "cocos2d.h" using namespace cocos2d; class HScore : public CCLayer { public: virtual bool init(); static CCScene * scene(); CREATE_FUNC(HScore); private: void backMenu(); }; #endif /* defined(__dafeiji__HScore__) */ HScore.cpp: // // HScore.cpp // dafeiji // // Created by 丁小未 on 13-9-25. // // #include "HScore.h" #include "HMenu.h" using namespace std; CCScene * HScore::scene() { CCScene * scene = CCScene::create(); CCLayer * layer = HScore::create(); scene->addChild(layer); return scene; } bool HScore::init() { if (!CCLayer::init()) { return false; } CCSize size = CCDirector::sharedDirector()->getWinSize(); //创建背景 CCSprite * sp = CCSprite::create("score_bg.png"); sp->setPosition(CCPointMake(size.width/2, size.height/2)); addChild(sp); string scoreStr = ""; string score = CCUserDefault::sharedUserDefault()->getStringForKey("user_score","-1").c_str();//如果没有值的话就默认为-1 //atoi接受的是一个c风格的字符串返回的是一个整形 //c_str是返回一个C类型的字符串 if (atoi(score.c_str())!=-1) { scoreStr+=score; } else{ scoreStr = "0"; } //分数 CCLabelTTF * ttfAbout = CCLabelTTF::create(scoreStr.c_str(), "Helvetica", 23); ttfAbout->setPosition(CCPointMake(size.width * 0.5 - 50, size.height * 0.5 + 40)); ttfAbout->setColor(ccRED); this->addChild(ttfAbout); //返回主菜单 CCLabelTTF * ttback = CCLabelTTF::create("返回主菜单","Helvetica", 23); //设置为黄色 ttback->setColor(ccc3(255, 255, 0)); CCMenuItemLabel *menuLabel = CCMenuItemLabel::create(ttback, this, menu_selector(HScore::backMenu)); menuLabel->setPosition(CCPointMake(0, -200)); CCMenu * menu = CCMenu::create(menuLabel,NULL); addChild(menu); return true; } void HScore::backMenu() { //自上而下翻滚切换 CCDirector::sharedDirector()->replaceScene(CCTransitionFadeDown::create(1.5, HMenu::scene())); } 8.关于作者场景的设计: HAbout.c: // // HAbout.h // dafeiji // // Created by 丁小未 on 13-9-25. // // #ifndef __dafeiji__HAbout__ #define __dafeiji__HAbout__ #include <iostream> #include "cocos2d.h" using namespace cocos2d; class HAbout : public CCLayer { public: virtual bool init(); static CCScene * scene(); CREATE_FUNC(HAbout); private: void backMenu(); }; #endif /* defined(__dafeiji__HAbout__) */ HAbout.cpp: // // HAbout.cpp // dafeiji // // Created by 丁小未 on 13-9-25. // // #include "HAbout.h" #include "HMenu.h" #include "SimpleAudioEngine.h" using namespace CocosDenshion; CCScene * HAbout::scene() { CCScene * scene = CCScene::create(); CCLayer * layer = HAbout::create(); scene->addChild(layer); return scene; } bool HAbout::init() { if (!CCLayer::init()) { return false; } CCSize size = CCDirector::sharedDirector()->getWinSize(); //添加背景 CCSprite * sp = CCSprite::create("score_bg.png"); sp->setPosition(CCPointMake(size.width/2, size.height/2)); addChild(sp); //添加返回菜单 CCLabelTTF * ttback = CCLabelTTF::create("返回主菜单", "Helvetica-bold", 23); ttback->setColor(ccc3(255, 255, 0)); //返回菜单项 CCMenuItemLabel * menuLabel = CCMenuItemLabel::create(ttback, this, menu_selector(HAbout::backMenu)); menuLabel->setPosition(CCPointMake(0, -200)); CCMenu *menu = CCMenu::create(menuLabel,NULL); addChild(menu); return true; } //返回主菜单 void HAbout::backMenu() { //翻页切换 CCDirector::sharedDirector()->replaceScene(CCTransitionPageTurn::create(1.5, HMenu::scene(), true)); } 运行效果: 如何修适应安卓机? 1.在AppDelegate的applicationDidFinishLaunching方法中添加这么一行屏幕分辨率自适应: CCEGLView::sharedOpenGLView()->setDesignResolutionSize(320,480,kResolutionUnKnown); 2.还有在eclipse中修改一个AndroidManifest.xml文件, 屏幕默认是横屏的,如果要修改成纵屏,则修改android:screenOrientation="portrait" 项目源码:http://download.csdn.net/detail/s10141303/6334027 已经编译成的安卓项目:http://download.csdn.net/detail/s10141303/6422971 或者加群获得源码 cocos2d-x游戏开发QQ交流群:280818155 备注:加入者必须修改:地区-昵称,很少有动态的将定期清理 ==================== 迂者 丁小未 CSDN博客专栏================= MyBlog:http://blog.csdn.net/dingxiaowei2013 MyQQ:1213250243 Unity QQ群:858550 cocos2dx QQ群:280818155 ======================相互学习,共同进步=================== 转载请注明出处:http://blog.csdn.net/dingxiaowei2013/article/details/12111867 欢迎关注我的微博: http://weibo.com/u/2590571922 本文转蓬莱仙羽51CTO博客,原文链接:http://blog.51cto.com/dingxiaowei/1366255,如需转载请自行联系原作者

优秀的个人博客,低调大师

[IOS]网络操作+图片的下载和读取+json数据读取

如何读取沙盒中的文件,和保存网络资源到沙盒中? -(NSString*)dataFilePath:(NSString*)fileName { NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString*document=[pathsobjectAtIndex:0]; return[documentstringByAppendingPathComponent:fileName]; } -(void)connectionDidFinishLoading:(NSURLConnection*)connection { //可以下载图片 [self.datawriteToFile:[selfdataFilePath:@"image.jpg"]atomically:YES]; self.webView.hidden=YES; //将沙盒中的图片加载到界面中 NSString*path = [selfdataFilePath:@"image.jpg"]; UIImage*imag = [[UIImagealloc]initWithContentsOfFile:path]; UIImageView*img = [[UIImageViewalloc]initWithImage:imag]; CGRectrect =CGRectMake(0,0,320,460); img.frame= rect; [self.viewaddSubview:img]; } 进入主题,接下来我要实现三个功能: 1.访问网页 2.从网上加载图片资源到本地 3.发送get请求获取到天气预报的接口,然后保存到本地接着是json解析 功能设计: 1.webView的使用 PageViewController.h: #import <UIKit/UIKit.h> @interface PageViewController : UIViewController<UIWebViewDelegate> @property (retain, nonatomic) IBOutlet UIWebView *webView; - (IBAction)GoClick:(id)sender; @property (retain, nonatomic) IBOutlet UITextField *txtUrl; - (IBAction)resignBoardClick:(id)sender; @property(retain,nonatomic)NSURL *url; @property(nonatomic,retain)UIAlertView *alert; @end PageViewController.m: // // PageViewController.m // 地图+网络 // // Created by 丁小未 on 13-8-27. // Copyright (c) 2013年 dingxiaowei. All rights reserved. // #import "PageViewController.h" @interface PageViewController () @end @implementation PageViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.title = @"页面"; } return self; } -(void)pageLoad1:(NSURL *)url { NSURLRequest *request = [NSURLRequest requestWithURL:url]; [self.webView loadRequest:request]; } - (void)viewDidLoad { [super viewDidLoad]; self.url = [NSURL URLWithString:@"http://www.baidu.com"]; NSURLRequest *request = [NSURLRequest requestWithURL:self.url]; [self pageLoad1:self.url]; } -(void)webViewDidFinishLoad:(UIWebView *)webView { [self.alert dismissWithClickedButtonIndex:0 animated:YES]; } -(void)webViewDidStartLoad:(UIWebView *)webView { self.alert = [[UIAlertView alloc] initWithTitle:@"Loading..." message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles: nil]; [self.alert show]; UIActivityIndicatorView *aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; aiv.center = CGPointMake(self.alert.bounds.size.width/2, self.alert.bounds.size.height/2); [aiv startAnimating]; [self.alert addSubview:aiv]; } - (void)dealloc { [_webView release]; [_url release]; [_txtUrl release]; [_alert release]; [super dealloc]; } - (IBAction)GoClick:(id)sender { [self.txtUrl resignFirstResponder]; if (self.txtUrl.text != nil) { self.url = [NSURL URLWithString:self.txtUrl.text]; [self pageLoad1:self.url]; } else { self.alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"地址不能为空" delegate:self cancelButtonTitle:@"OK"otherButtonTitles: nil]; [self.alert show]; } } - (IBAction)resignBoardClick:(id)sender { [self.txtUrl resignFirstResponder]; } @end xib: 效果图: 请求网络的加载效果: 请求结束的效果图: 2.根据URL地址请求网络图片并且显示出来 PicViewController.h: // // PicViewController.h // 地图+网络 // // Created by 丁小未 on 13-8-27. // Copyright (c) 2013年 dingxiaowei. All rights reserved. // #import <UIKit/UIKit.h> @interface PicViewController : UIViewController<UIWebViewDelegate,NSURLConnectionDataDelegate> @property(nonatomic,retain)NSURL *url; @property (retain, nonatomic) IBOutlet UIWebView *webView; @property (retain, nonatomic) NSMutableData * data; @property (retain, nonatomic) NSURLConnection * connection; @end PicViewController.m: // // PicViewController.m // 地图+网络 // // Created by 丁小未 on 13-8-27. // Copyright (c) 2013年 dingxiaowei. All rights reserved. // #import "PicViewController.h" @interface PicViewController () @end @implementation PicViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; NSString *urlString =@"http://e.hiphotos.baidu.com/album/w%3D2048/sign=76d548844afbfbeddc59317f4cc8f636/267f9e2f07082838334a05afb999a9014d08f1c2.jpg"; self.url = [NSURL URLWithString:urlString]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:self.url]; [self.webView loadRequest:request]; //step3:创建链接 self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if(self.connection) { NSLog(@"创建链接成功"); }else{ NSLog(@"创建链接失败"); } [urlString release]; } //获取数据 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSMutableData * data = [[NSMutableData alloc] init]; self.data = data; [data release]; } //不断的获取数据 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //接受返回数据,这个方法可能会被调用多次,因此将多次返回数据加起来 NSInteger datalength = [data length]; NSLog(@"返回数据量:%d",datalength); [self.data appendData:data]; } //获取文件地址 -(NSString *)dataFilePath:(NSString*)fileName { NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *document=[paths objectAtIndex:0]; return [document stringByAppendingPathComponent:fileName]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { //可以下载图片 [self.data writeToFile:[self dataFilePath:@"image.jpg"] atomically:YES]; self.webView.hidden = YES; //将沙盒中的图片加载到界面中 NSString *path = [self dataFilePath:@"image.jpg"]; UIImage *imag = [[UIImage alloc] initWithContentsOfFile:path]; UIImageView *img = [[UIImageView alloc] initWithImage:imag]; CGRect rect = CGRectMake(0, 0, 320,460); img.frame = rect; [self.view addSubview:img]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"连接失败"); } - (void)dealloc { [_webView release]; [super dealloc]; } @end xib: 请求后的效果图: 3.请求天气预报的接口然后json解析请求后的数据并且保存到本地显示出来 WeatherViewController.h: // // WeatherViewController.h // 地图+网络 // // Created by 丁小未 on 13-8-27. // Copyright (c) 2013年 dingxiaowei. All rights reserved. // #import <UIKit/UIKit.h> @interface WeatherViewController : UIViewController<UIWebViewDelegate,NSURLConnectionDataDelegate> @property (retain, nonatomic) IBOutlet UITextField *txtCity; @property (retain, nonatomic) IBOutlet UITextField *txtMaxTem; @property (retain, nonatomic) IBOutlet UITextField *txtMinTem; @property (retain, nonatomic) IBOutlet UITextField *txtTempreture; @property(retain,nonatomic)NSMutableData *data; @property (retain, nonatomic) IBOutlet UILabel *label; @property(retain,nonatomic)NSURLConnection *connection; - (IBAction)resignBoard:(id)sender; @end WeatherViewController.m: // // WeatherViewController.m // 地图+网络 // // Created by 丁小未 on 13-8-27. // Copyright (c) 2013年 dingxiaowei. All rights reserved. // #import "WeatherViewController.h" @interface WeatherViewController () @end @implementation WeatherViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { } return self; } - (void)viewDidLoad { [super viewDidLoad]; self.label.text = @"正在请求数据"; NSString *urlString = @"http://www.weather.com.cn/data/cityinfo/101020100.html"; NSURL *url = [NSURL URLWithString:urlString]; //实例化一个request NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; //创建连接 self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (self.connection) { NSLog(@"创建连接成功"); } else { NSLog(@"创建连接失败"); } [url release]; [urlString release]; } //获取数据 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { //接受一个服务端回话,再次一般初始化接受数据的对象 //NSLog(@"返回数据类型%@",[response ]); //NSLog(@"返回数据编码%@",[response text]); NSMutableData * data = [[NSMutableData alloc] init]; self.data = data; [data release]; } //不断的获取数据 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //接受返回数据,这个方法可能会被调用多次,因此将多次返回数据加起来 NSInteger datalength = [data length]; NSLog(@"返回数据量:%d",datalength); [self.data appendData:data]; } //获取文件地址 -(NSString *)dataFilePath:(NSString*)fileName { NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *document=[paths objectAtIndex:0]; return [document stringByAppendingPathComponent:fileName]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { //连接结束 NSLog(@"%d",[self.data length]); self.label.text =@"天气预报"; //可以下载图片 //[self.data writeToFile:[self dataFilePath:@"image.jpg"] atomically:YES]; // NSString * mystr = [[NSStringalloc] initWithData:self.dataencoding:NSUTF8StringEncoding]; // // [mystr writeToFile:[selfdataFilePath:@"百度图片—全球最大中文图片库.html"] atomically:YES encoding:NSUTF8StringEncoding error:nil]; // // NSLog(@"最后的结果%@",mystr); // // [mystr release]; NSDictionary *weather = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil]; NSLog(@"%@",weather); [weather writeToFile:[self dataFilePath:@"weather.plist"] atomically:YES]; NSLog(@"%@",[weather allKeys]); NSDictionary *dic = [weather objectForKey:@"weatherinfo"]; NSLog(@"%@",dic); self.txtCity.text = [dic objectForKey:@"city"]; self.txtTempreture.text = [dic objectForKey:@"weather"]; self.txtMaxTem.text = [dic objectForKey:@"temp2"]; self.txtMinTem.text = [dic objectForKey:@"temp1"]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { self.label.text =@"连接失败"; } - (void)dealloc { [_txtCity release]; [_txtMaxTem release]; [_txtMinTem release]; [_txtTempreture release]; [_label release]; [super dealloc]; } - (IBAction)resignBoard:(id)sender { [self.txtMaxTem resignFirstResponder]; [self.txtMinTem resignFirstResponder]; [self.txtCity resignFirstResponder]; [self.txtTempreture resignFirstResponder]; } @end xib: 请求网络后的效果图: Demo源文件下载(猛戳) 本文转蓬莱仙羽51CTO博客,原文链接:http://blog.51cto.com/dingxiaowei/1366414,如需转载请自行联系原作者

优秀的个人博客,低调大师

苹果iOS开发深入浅出Cocoa之类与对象

最近打算写一些ObjC中比较底层的东西,尤其是 runtime 相关的。苹果已经将 ObjC runtime 代码开源了,我们可以从:http://opensource.apple.com/source/objc4/objc4-493.9/runtime/浏览源代码,或点此下载源代码。 从哪里入手呢?那当然是最基本的类与对象。与C++相比,ObjC中的类与对象结构要简洁与一致得多(参考《深度探索C++对象模型》,你就知道C++中类与对象结构的复杂)。本文将详细讲解ObjC中类与对象的结构,下回将讲如何在 runtime 时操作类。 我们可以在/usr/include/objc/objc.h 和 runtime.h 中找到对 class 与 object 的定义: typedef struct objc_class *Class; typedef struct objc_object { Class isa; } *id; Class 是一个 objc_class 结构类型的指针;而 id(任意对象) 是一个 objc_object 结构类型的指针,其第一个成员是一个 objc_class 结构类型的指针。注意这里有一关键的引申解读:内存布局以一个 objc_class 指针为开始的所有东东都可以当做一个 object 来对待! 那 objc_class 又是怎样一个结构体呢?且看: struct objc_class { struct objc_class* isa; struct objc_class* super_class; const char* name; long version; long info; long instance_size; struct objc_ivar_list* ivars; struct objc_method_list** methodLists; struct objc_cache* cache; struct objc_protocol_list* protocols; } objc_class 结构体的各成员介绍如下: isa:是一个 objc_class 类型的指针,看到这里,想起我前面的引申解读了没?内存布局以一个 objc_class 指针为开始的所有东东都可以当做一个 object 来对待! 这就是说 objc_class 或者说类其实也可以当做一个 objc_object 对象来对待!对象是对象,类也是对象,是不是有点混淆?别急,ObjC发明(or 重用)了一个术语来区分这两种不同的对象:类对象(class object)与实例对象(instance object)。OK,名称混淆的问题解决,下面我将使用这两个术语来区分不同的对象,而使用“对象”这一术语来泛指所有的对象。ObjC还对类对象与实例对象中的 isa 所指向的类结构作了不同的命名:类对象中的 isa 指向类结构被称作 metaclass,metaclass 存储类的static类成员变量与static类成员方法(+开头的方法);实例对象中的 isa 指向类结构称作 class(普通的),class 结构存储类的普通成员变量与普通成员方法(-开头的方法)。 super_class:一看就明白,指向该类的父类呗!如果该类已经是最顶层的根类(如 NSObject 或 NSProxy),那么 super_class 就为 NULL。 好,先中断一下其他类结构成员的介绍,让我们厘清一下在继承层次中,子类,父类,根类(这些都是普通 class)以及其对应的 metaclass 的 isa 与 super_class 之间关系: 规则一:类的实例对象的 isa 指向该类;该类的 isa 指向该类的 metaclass; 规则二:类的 super_class 指向其父类,如果该类为根类则值为 NULL; 规则三:metaclass 的 isa 指向根 metaclass,如果该 metaclass 是根 metaclass 则指向自身; 规则四:metaclass 的 super_class 指向父 metaclass,如果该 metaclass 是根 metaclass 则指向该 metaclass 对应的类; 好吧,文字总是那么乏力,有图有真相! 那么 class 与 metaclass 有什么区别呢? class 是 instance object 的类类型。当我们向实例对象发送消息(实例方法)时,我们在该实例对象的 class 结构的 methodlists 中去查找响应的函数,如果没找到匹配的响应函数则在该 class 的父类中的 methodlists 去查找(查找链为上图的中间那一排)。如下面的代码中,向str 实例对象发送 lowercaseString 消息,会在 NSString 类结构的 methodlists 中去查找 lowercaseString 的响应函数。 NSString * str;[str lowercaseString]; metaclass 是 class object 的类类型。当我们向类对象发送消息(类方法)时,我们在该类对象的 metaclass 结构的 methodlists 中去查找响应的函数,如果没有找到匹配的响应函数则在该 metaclass 的父类中的 methodlists 去查找(查找链为上图的最右边那一排)。如下面的代码中,向 NSString 类对象发送 stringWithString 消息,会在 NSString 的 metaclass 类结构的 methodlists 中去查找 stringWithString 的响应函数。 [NSString stringWithString:@"str"]; 好,至此我们明白了类的结构层次,让我们接着看类结构中的其他成员。 name:一个 C 字符串,指示类的名称。我们可以在运行期,通过这个名称查找到该类(通过:id objc_getClass(const char *aClassName))或该类的 metaclass(id objc_getMetaClass(const char *aClassName)); version:类的版本信息,默认初始化为 0。我们可以在运行期对其进行修改(class_setVersion)或获取(class_getVersion)。 info:供运行期使用的一些位标识。有如下一些位掩码: CLS_CLASS (0x1L) 表示该类为普通 class ,其中包含实例方法和变量; CLS_META (0x2L) 表示该类为 metaclass,其中包含类方法; CLS_INITIALIZED (0x4L) 表示该类已经被运行期初始化了,这个标识位只被 objc_addClass 所设置; CLS_POSING (0x8L) 表示该类被 pose 成其他的类;(poseclass 在ObjC 2.0中被废弃了); CLS_MAPPED (0x10L) 为ObjC运行期所使用 CLS_FLUSH_CACHE (0x20L) 为ObjC运行期所使用 CLS_GROW_CACHE (0x40L) 为ObjC运行期所使用 CLS_NEED_BIND (0x80L) 为ObjC运行期所使用 CLS_METHOD_ARRAY (0x100L) 该标志位指示 methodlists 是指向一个 objc_method_list 还是一个包含 objc_method_list 指针的数组; instance_size:该类的实例变量大小(包括从父类继承下来的实例变量); ivars:指向 objc_ivar_list 的指针,存储每个实例变量的内存地址,如果该类没有任何实例变量则为 NULL; methodLists:与 info 的一些标志位有关,CLS_METHOD_ARRAY 标识位决定其指向的东西(是指向单个 objc_method_list还是一个 objc_method_list 指针数组),如果 info 设置了 CLS_CLASS 则 objc_method_list 存储实例方法,如果设置的是 CLS_META 则存储类方法; cache:指向 objc_cache 的指针,用来缓存最近使用的方法,以提高效率; protocols:指向 objc_protocol_list 的指针,存储该类声明要遵守的正式协议。 总结: ObjC 为每个类的定义生成两个 objc_class ,一个即普通的 class,另一个即 metaclass。我们可以在运行期创建这两个 objc_class 数据结构,然后使用 objc_addClass 动态地创建新的类定义。这个够动态够强大的吧?下回讲演示如何在运行期动态创建新类。 本文转自 wws5201985 51CTO博客,原文链接:http://blog.51cto.com/wws5201985/782033,如需转载请自行联系原作者

优秀的个人博客,低调大师

【原/转】iOS中非常强大的过滤器:NSPredicate

在APPLE的官方Demo:UICatalog中实现UISearchBar模糊搜索功能是这么做的: 1 - (void)viewDidLoad { 2 [super viewDidLoad]; 3 4 self.allResults = @[@"Here's", @"to", @"the", @"crazy", @"ones.", @"The", @"misfits.", @"The", @"rebels.", @"The", @"troublemakers.", @"The", @"round", @"pegs", @"in", @"the", @"square", @"holes.", @"The", @"ones", @"who", @"see", @"things", @"differently.", @"They're", @"not", @"fond", @"of", @"rules.", @"And", @"they", @"have", @"no", @"respect", @"for", @"the", @"status", @"quo.", @"You", @"can", @"quote", @"them,", @"disagree", @"with", @"them,", @"glorify", @"or", @"vilify", @"them.", @"About", @"the", @"only", @"thing", @"you", @"can't", @"do", @"is", @"ignore", @"them.", @"Because", @"they", @"change", @"things.", @"They", @"push", @"the", @"human", @"race", @"forward.", @"And", @"while", @"some", @"may", @"see", @"them", @"as", @"the", @"crazy", @"ones,", @"we", @"see", @"genius.", @"Because", @"the", @"people", @"who", @"are", @"crazy", @"enough", @"to", @"think", @"they", @"can", @"change", @"the", @"world,", @"are", @"the", @"ones", @"who", @"do."]; 5 6 self.visibleResults = self.allResults; 7 } 1 - (void)setFilterString:(NSString *)filterString { 2 _filterString = filterString; 3 4 if (!filterString || filterString.length <= 0) { 5 self.visibleResults = self.allResults; 6 } 7 else { 8 NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"self contains[c] %@", filterString]; 9 self.visibleResults = [self.allResults filteredArrayUsingPredicate:filterPredicate]; 10 } 11 12 [self.tableView reloadData]; 13 } 其中,self.allResults是列表的全部结果,self.visibleResults是输入搜索词后出现的模糊匹配结果。流程如下图所示: 从上述代码可以看到,APPLE获取到模糊搜索结果所用的代码仅仅两行。由此可见,NSPredicate的功能不可小觑。这也是本文的目的,全方位地介绍一下在cocoa框架下的搜索匹配利器:NSPredicate。Cocoa框架中的NSPredicate用于查询,原理和用法都类似于SQL中的where,作用相当于数据库的过滤取。 1、初始化 1 NSPredicate *ca = [ NSPredicate predicateWithFormat:( NSString *), ...]; 那传入的初始化NSString到底要满足怎样的格式呢? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 (1)比较运算符>,<,==,>=,<=,!= 可用于数值及字符串 例:@ "number > 100" (2)范围运算符:IN、BETWEEN 例:@ "number BETWEEN {1,5}" @ "address IN {'shanghai','beijing'}" (3)字符串本身:SELF 例:@“SELF == ‘APPLE’" (4)字符串相关:BEGINSWITH、ENDSWITH、CONTAINS 例:@ "name CONTAIN[cd] 'ang'" //包含某个字符串 @ "name BEGINSWITH[c] 'sh'" //以某个字符串开头 @ "name ENDSWITH[d] 'ang'" //以某个字符串结束 注:[c]不区分大小写,[d]不区分发音符号即没有重音符号,[cd]既不区分大小写,也不区分发音符号。 (5)通配符:LIKE 例:@ "name LIKE[cd] '*er*'" //*代表通配符,Like也接受[cd]. @ "name LIKE[cd] '???er*'" (6)正则表达式:MATCHES 例: NSString *regex = @ "^A.+e$" ; //以A开头,e结尾 @ "name MATCHES %@" ,regex 2、使用 2.1 场景1:NSArray过滤,也就是文章开头的场景 1 2 3 4 NSArray *array = [[ NSArray alloc]initWithObjects:@ "beijing" ,@ "shanghai" ,@ "guangzou" ,@ "wuhan" , nil ]; NSString *string = @ "ang" ; NSPredicate *pred = [ NSPredicate predicateWithFormat:@ "SELF CONTAINS %@" ,string]; NSLog (@ "%@" ,[array filteredArrayUsingPredicate:pred]); 2.2 场景2:判断字符串首字母是否为字母 1 2 3 4 5 NSString *regex = @ "[A-Za-z]+" ; NSPredicate *predicate = [ NSPredicate predicateWithFormat:@ "SELF MATCHES %@" , regex]; if ([predicate evaluateWithObject:aString]) { } 2.3 场景3:字符串替换 1 2 3 4 5 6 7 8 9 10 11 NSError * error = NULL ; NSRegularExpression * regex = [ NSRegularExpression regularExpressionWithPattern:@ "(encoding=\")[^\"]+(\")" options:0 error:&error]; NSString * sample = @ "<xml encoding=\"abc\"></xml><xml encoding=\"def\"></xml><xml encoding=\"ttt\"></xml>" ; NSLog (@ "Start:%@" ,sample); NSString * result = [regex stringByReplacingMatchesInString:sample options:0 range: NSMakeRange (0, sample.length) withTemplate:@ "$1utf-8$2" ]; NSLog (@ "Result:%@" , result); 2.4 场景4:截取字符串 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 //组装一个字符串,需要把里面的网址解析出来 NSString *urlString=@ "<meta/><link/><title>1Q84 BOOK1</title></head><body>" ; //NSRegularExpression类里面调用表达的方法需要传递一个NSError的参数。下面定义一个 NSError *error; //http+:[^\\s]* 这个表达式是检测一个网址的。(?<=title\>).*(?=</title)截取html文章中的<title></title>中内文字的正则表达式 NSRegularExpression *regex = [ NSRegularExpression regularExpressionWithPattern:@ "(?<=title\\>).*(?=</title)" options:0 error:&error]; if (regex != nil ) { NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options:0 range: NSMakeRange (0, [urlString length])]; if (firstMatch) { NSRange resultRange = [firstMatch rangeAtIndex:0]; //从urlString当中截取数据 NSString *result=[urlString substringWithRange:resultRange]; //输出结果 NSLog (@ "->%@<-" ,result); } } 2.5 场景5:判断是否是手机号码或者电话号码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 //组装一个字符串,需要把里面的网址解析出来 NSString *urlString=@ "<meta/><link/><title>1Q84 BOOK1</title></head><body>" ; //NSRegularExpression类里面调用表达的方法需要传递一个NSError的参数。下面定义一个 NSError *error; //http+:[^\\s]* 这个表达式是检测一个网址的。(?<=title\>).*(?=</title)截取html文章中的<title></title>中内文字的正则表达式 NSRegularExpression *regex = [ NSRegularExpression regularExpressionWithPattern:@ "(?<=title\\>).*(?=</title)" options:0 error:&error]; if (regex != nil ) { NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options:0 range: NSMakeRange (0, [urlString length])]; if (firstMatch) { NSRange resultRange = [firstMatch rangeAtIndex:0]; //从urlString当中截取数据 NSString *result=[urlString substringWithRange:resultRange]; //输出结果 NSLog (@ "->%@<-" ,result); } } 2.6 场景6:验证邮箱、电话号码有效性 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 //是否是有效的正则表达式 +( BOOL )isValidateRegularExpression:( NSString *)strDestination byExpression:( NSString *)strExpression { NSPredicate *predicate = [ NSPredicatepredicateWithFormat :@ "SELF MATCHES %@" , strExpression]; return [predicate evaluateWithObject:strDestination]; } //验证email +( BOOL )isValidateEmail:( NSString *)email { NSString *strRegex = @ "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{1,5}" ; BOOL rt = [CommonTools isValidateRegularExpression:email byExpression:strRegex]; return rt; } //验证电话号码 +( BOOL )isValidateTelNumber:( NSString *)number { NSString *strRegex = @ "[0-9]{1,20}" ; BOOL rt = [CommonTools isValidateRegularExpression:number byExpression:strRegex]; return rt; } 2.7 场景7:NSDate筛选 1 2 3 4 5 6 7 8 9 10 11 12 13 //日期在十天之内: NSDate *endDate = [[ NSDate date] retain]; NSTimeInterval timeInterval= [endDate timeIntervalSinceReferenceDate]; timeInterval -=3600*24*10; NSDate *beginDate = [[ NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval] retain]; //对coredata进行筛选(假设有fetchRequest) NSPredicate *predicate_date = [ NSPredicate predicateWithFormat:@ "date >= %@ AND date <= %@" , beginDate,endDate]; [fetchRequest setPredicate:predicate_date]; //释放retained的对象 [endDate release]; [beginDate release]; 本文转自编程小翁博客园博客,原文链接:http://www.cnblogs.com/wengzilin/p/4276612.html,如需转载请自行联系原作者

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码