iOS学习03

Posted 轻舟一曲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS学习03相关的知识,希望对你有一定的参考价值。

ios学习03

53章

数据持久化

应用程序的数据持久化。


1、数据库网络获得沙盒SanBox路径。

创建单视图应用程序。

获得沙盒路径,即手机上的路径。

//AppDelegate.m
@interface
-(IBAction)homeTap:(id)sender;
@property(weak,nonatomic)IBOutlet UITextView * msgText;
//ViewController.m
-(void)viewDidLoad
    [super viewDidLoad];
    NSString * path=NSHomeDirectory();
    path=[path stringByAppendingPathComponent:@"abc.txt"];
    NSLog(@"%@",path);
    
    NSString * str=@"1234";
    //[str writeToFile:@"abc.txt" atomically:YES];//用这种方式创建不了沙盒路径下的文件
    [str writeToFile:path atomically:YES];//在应用程序的可执行文件路径下写入该文件

-(IBAction)homeTap:(id)sender
    //NSLog(@"xxxx")
    self.msgText.text=NSHomeDirectory();


2、应用程序路径的变化。

//ViewController.m
-(void)viewDidLoad
    [super viewDidLoad];
    //NSString * path=NSHomeDirectory();//每运行一次都在改变,有潜在危险,一般只读
    //NSLog(@"%@",path);
    NSArray * paths=NSSearchPathForDirectioriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString * documentsDirectory=[paths objectAtIndex:0];
    NSLog(@"%@",documentsDirectory);
    NSString * filePath=[documentsDirectory stringByAppendingPathComponent:@"aa.txt"];
    /*
    NSString * str=@"12345";
    if([str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil])
        NSLog(@"创建成功");
    
    else
        NSLog(@"创建失败");
    
    */
    NSString * str=[NSStirng stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",str);


3、数据库网络之plist文件保存。

按住option键复制一个按钮。

@interface
-(IBAction)homeTap:(id)sender;
@property(weak,nonatomic)IBOutlet UITextView * msgText;
-(IBAction)docTap:(id)sender;
-(IBAction)libTap:(id)sender;
-(IBAction)tmpTap:(id)sender;
//ViewController.m
-(void)viewDidLoad
    [super viewDidLoad];
    NSString * path=NSHomeDirectory();
    path=[path stringByAppendingPathComponent:@"abc.plist"];//abc.txt
    /*
    NSLog(@"%@",path);
    NSString * str=@"1234";
    //[str writeToFile:@"abc.txt" atomically:YES];//用这种方式创建不了沙盒路径下的文件
    [str writeToFile:path atomically:YES];//在应用程序的可执行文件路径下写入该文件
    
    //除了上述文件的方式保存数据外,还可以采用集合的方式
    NSArray * array=[NSArray arrayWithObjects:@"1",@"2",@"33",nil];
    [array writeToFile:path atomically:YES];
    */
    NSDictionary * dict=[NSDictionary dictionaryWithObjectsAndKeys:@"张",@"name",@"12",@"age",nil];
    [dict writeToFile:path atomically:YES];
    //写文件时如果是自定义的类,则需要进行归档处理
    

-(IBAction)homeTap:(id)sender
    //NSLog(@"xxxx")
    self.msgText.text=NSHomeDirectory();

-(IBAction)docTap:(id)sender
  NSArray * array=NSSearchForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);//搜索路径在当前Domains下,在那个路径下搜索,在当前用户目录下搜索,路径是否展开
    NSLog(@"%@",[array objectAtIndex:0]);
   self.msgText.text=@"";
   self.msgText.text=[array objectAtIndex:0];//  \\d可能被当做转义

-(IBAction)libTap:(id)sender
      NSArray * array=NSSearchForDirectoriesInDomains(NSLibraryirectory,NSUserDomainMask,YES);
   self.msgText.text=@"";
   self.msgText.text=[array objectAtIndex:0];

-(IBAction)tmpTap:(id)sender
   self.msgText.text=NSTemporaryDirectory();


4、数据库网络之NSUserDefaults用户默认保存。

如何在iOS中进行数据的保存,要将数据长久保存必须依靠文件,在iOS中要想使用文件,首先必须获得当前文件进行保存的路径,iOS中是一种沙盒机制,一个应用程序在磁盘对应自己有自己的空间,这个空间不能被别人访问,即应用程序之间不能进行数据共享。

创建单视图应用程序。登录成功后密码保存。

//AppDelegate.m
@interface
@property (weak,nonatomic)IBOutlet UITextField * uname;
-(IBAction)loginTap:(id)sender;
-(IBAction)deleteTap:(id)sender;//删除默认事件
//ViewController.m
-(void)viewDidLoad
    [super viewDidLoad];
    /*
    //是否已经正确登录过
    NSString * path=NSHomeDirectory();//当前应用程序的根目录
    path=[path stringByAppendingPathCompoent:@"save.txt"];
    NSLog(@"path=%@",path);//刚开始没有这个文件,需要写过文件才会创建出这个文件
    NSString * uname=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    if(uname==nil)
        NSLog(@"还没保存过");
    
    else
        self.uname.text=uname;
    
    */
    //第二种手段:采用用户默认保存的方式  NSUserDefaults本质是一个字典
    NSString * uname=[[NSUserDefaults standardUserDefaults]objectForKey:@"USERNAME"];
    if(uname==nil)
        NSLog(@"还没保存过");
    
    else
        self.uname.text=uname;
    

-(IBAction)loginTap:(id)sender
    NSString * str=self.uname.text;
    if(str.length>0)
        /*
         NSString * path=NSHomeDirectory();
         path=[path stringByAppendingPathCompoent:@"save.txt"];
         [str writeToFile:path atomically:YES];
         */
         [[NSUserDefaults standardUserDefaults]setObject:str forKey:@"USERNAME"];
    

-(IBAction)deleteTap:(id)sender
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"USERNAME"];

54章

sqlite


安装数据库工具。Navicat for SQLite。

1、运行navicat for sqlite

2、新建一个连接(连接名,数据库的路径和它的文件名字)

3、保存信息。每行叫记录,每列叫记录。

创建一个表:


ddl  结构定义 create alter drop 
dml  数据操作 insert delete update select
create table t_cjb(xingming text not null,yuwen integer not null,shuxue integer not null,yingyu integer not null);
/*
real表示小数点
*/
create table if not exists feiyong(id integer,fy real);

-- 插入数据 只能插入一行
-- insert into 表名(字段列表)values(值的列表)
insert into t_student(name,telnum) values('11','22')
-- 修改数据
-- update 表名 set 字段名=值 .. where 条件
update t_student set telnum='138' where name='11'
-- 删除数据
-- delete from 表名 where 条件
delete from t_student where name='11'

-- 查询语句
-- select 字段列表 from 表名 where 条件 order by 字段名
select * from t_student -- *显示所有列
select name as 姓名 from t_student
select name 姓名 from t_student where name='张'
select * from t_student where name like '张%'
select count(*) from t_student where age<20
select * from t_student where age<20 and age>10 -- age<20 or age>10
select * from t_student where order by age --升序
select * from t_student where age<20 order by age desc --降序
select sum(yw) from t_student -- 统计函数
select avg(yw) from t_student 
select * ,yw+sx+yy as 总分 from t_student -- 计算列

如何在程序中使用数据库。创建单视图应用程序。选择工程,编译阶段,选中链接库。

-(IBAction)dbTap:(id)sender;
@property(weak,nonatomic)IBOutlet UITextField * nameText;
@property(weak,nonatomic)IBOutlet UITextField * ageText;
//ViewController.m
#import <sqlite3.h>
-(IBAction)dbTap:(id)sender
    //操作数据库 1、打开数据库,2、操作数据库,3、关闭数据库
    //提供c的字符串,即我们要打开的数据库的完整路径和文件名
    NSString * path=NSHomeDirectory();//获取沙盒路径
    path=[path stringAppendingPathComponent:@"mydb.sqlite"];//往路径增加文件名
    NSLog(@"%@",path);
    sqlite3 * db;//数据库指针
    //open如果没有这个数据库,并创建这个数据库文件并打开
    if(sqlite3_open([path UTF8String],&db)!=SQLITE_OK)
        NSLog(@"打开失败");
    
    //定制sql
    char * sql="create table if not exists t_student(name text,age integer)";
    char * err;//定制出错字符串
    if(sqlite3_exec(db,sql,NULL,NULL,&err)!=SQLITE_OK)
        NSLog(@"sql运行失败:%s",err);
    
    //增,删,改
    NSString * name=self.nameText.text;
    NSString * age=self.ageText.text;
    //sql="insert into t_student(name,age) values('张三',22)";
    /*NSString sql2=[NSString stringWithFormat:@"insert into t_student(name,age) values('%@',%@)",name,age];//动态sql,带'输入时候运行失败,解决方法:预处理绑定
    NSLog(@"%@",sql2);
    if(sqlite3_exec(db,[sql2 UIF8String],NULL,NULL,&err)!=SQLITE_OK)
        NSLog(@"增加失败:%s",err);
    
    */
    sql="insert into t_student(name,age) values(?,?)";
    sqlite3_stmt * stmt;
    if(sqlite23_prepare_v2(db,sql,-1,&stmt,NULL)==SQLITE_OK)
        //绑定参数
        if(sqlite3_bind_text(stmt,1,[name UTF8String],-1,NULL)!=SQLITE_OK)
            NSLog(@"name绑定失败");
        
        if(sqlite3_bind_int(stmt,2,[age intValue])!=SQLITE_OK)
            NSLog(@"age绑定失败");
        
    
    if(sqlite3_step(stmt)!=SQLITE_DONE)
        NSLog(@"插入失败");
    
    
    /*
    sql="delete from t_student where name='123'";
    if(sqlite3_exec(db,sql,NULL,NULL,&err)!=SQLITE_OK)
        NSLog(@"删除失败:%s",err);
    */
    sql="delete from t_student where name=?"
    if(sqlite3_prepare_v2(db,sql,-1,&stmt,NULL)==SQLITE_OK)
        if(sqlite3_bind_text(stmt,1,[name UTF8String],-1,NULL)!=SQLITE_OK)
            NSLog(@"name绑定失败");
        
    
    if(sqlite3_step(stmt)!=SQLITE_DONE)
        NSLog(@"删除失败");
    
    
    
    /*
    sql="update t_student set age=50 where name='李四'";
    if(sqlite3_exec(db,sql,NULL,NULL,&err)!=SQLITE_OK)
        NSLog(@"修改失败:%s",err);
    */
    sql="update t_student set age=? where name=?"
    if(sqlite3_prepare_v2(db,sql,-1,&stmt,NULL)==SQLITE_OK)
        if(sqlite3_bind_int(stmt,1,[age intValue],-1,NULL)!=SQLITE_OK)
            NSLog(@"age绑定失败");
        
        if(sqlite3_bind_text(stmt,2,[name UTF8String],-1,NULL)!=SQLITE_OK)
            NSLog(@"name绑定失败");
        
    
    if(sqlite3_step(stmt)!=SQLITE_DONE)
        NSLog(@"修改失败");
    
    
    
    //查,查询之后如何得到表中数据
    sql="select * from t_student";
    //-1表示自己计算
    if(sqlite3_prepare_v2(db,sql,-1,&stmt,NULL)==SQLITE_Ok)
       //遍历返回结果
        while(sqlite3_step(stmt)==SQLITE_ROW)//得到一行
            char * name=(char *)sqlite3_column_text(stmt,0);//得到第几列
            int age=(int)sqlite3_column_int(stmt,1);
            NSString * strName=[NSString stringWithUTF8String:@"%s",name];
            NSLog(@"name=%@,age=%d",strName,age);
        
    
    else
        NSLog(@"预处理失败");
    
    
    
    sqlite3_finalize(stmt);//释放资源
    sqlite3_close(db);

55章

Core Data

iOS原带的Core Data数据库使用详解。


Core Data持久化工具能将对象直接存储到数据库中。创建单视图应用程序,勾选持久化框架。

APPDelegate.h

//AppDelegate.m
-(BOOL)appliaction:(UIAppliaction *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    NSLog(@"%@",NSHomeDirectory());//根路径
    NSLog(@"%@",[self applicationDocumentsDirectory]);//文档路径
    return YES;

表名首字母需要大写。

@interface
@property(weak,nonatomic)IBOutlet UITextField * name;
@property(weak,nonatomic)IBOutlet UITextField * age;
-(IBAction)add:(UIButton *)sender;
-(IBAction)find:(UIButton *)sender;//查询
-(IBAction)delete:(UIButton *)sender;
-(IBAction)update:(UIButton *)sender;
//ViewController.m
#import "AppDelegate.h"
-(void)viewDidLoad
   [super viewDidLoad];
   /*
   AppDelegate * app=[UIApplication shareApplication].delegate; //获得应用程序代理
   NSManagedObjectContext * context=app.manageObjectContext;//获得托管上下文对象,自动创建数据库。
   //定义一个托管对象,上下文就是数据库,实体就是表
   */

-(IBAction)add:(UIButton *)sender
   NSString * name=self.name.text;
   NSString * age=self.age.text;
   name=[name stringByTrimmingCharactersInset:[NScharacterSet WhitespaceCharacterSet]];
   age=[age stringByTrimmingCharactersInset:[NScharacterSet WhitespaceCharacterSet]];
   if([name isEqualToString:@""])
       UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"姓名不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:,nil];
       return;
   
   if([age isEqualToString:@""])
       UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示" message:@"年龄不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:,nil];
   
   
   
   AppDelegate * app=[UIApplication shareApplication].delegate; 
   NSManagedObjectContext * context=app.manageObjectContext;
   //定义一个托管对象
   NSManageObject * mo=[NSEntityDescription insertNewObjectForEntityForName:@"Student" inManageObjectContext:context];
   [mo setValue:name forKey:@"name"];
   NSNumber * num=[NSNumber numberWithInt:age.intValue];
   [mo setValue:num forKey:@"age"];
   [context insertObject:mo];
   NSError * error;
   if(![context save:&error])
       NSLog(@"error=%@",[error description]);
   
   else
       NSLog(@"插入成功!");
   


-(IBAction)find:(UIButton *)sender
   AppDelegate * app=[UIApplication shareApplication].delegate; 
   NSManagedObjectContext * context=app.manageObjectContext;
   //实体指的就是表
   NSEnttityDescriptiotn * entity=[NSEntityDescription entityForName:@"Student" inManageObjectContext:context];
   //NSFetchRequest * request=[NSFetchRequest fetchRequestWithEntityName:entity];
   NSFetchRequest * request=[[NSFetchRequest alloc]init];
   [request setEntity:entity];
   
   //谓词
   NSString * pred=[NSpredicate predicateWIthFormat:@"(age=%d)",22];
   [request setPredicate:pred];
   
   NSError * error=nil;
   NSArray * objects=[context executeFetchRequest:request error:&error];
   if(objects)//查询成功
       NSLog(@"%ld",objects.count);
       for(NSManagedObejct * mo in objects)//每个学生信息
           NSLog(@"name=%@,age=%@",[mo valueForKey:@"name"],[mo valueForKey:@"age"]);
       
   


-(IBAction)delete:(UIButton *)sender
   AppDelegate * app=[UIApplication shareApplication].delegate; 
   NSManagedObjectContext * context=app.manageObjectContext;
   NSEnttityDescriptiotn * entity=[NSEntityDescription entityForName:@"Student" inManageObjectContext:context];
   NSFetchRequest * request=[[NSFetchRequest alloc]init];
   [request setEntity:entity];
   NSString * pred=[NSpredicate predicateWIthFormat:@"(age=%d)",22];
   [request setPredicate:pred];
   
   NSError * error=nil;
   NSArray * objects=[context executeFetchRequest:request error:&error];
   if(objects)//查询成功
       NSLog(@"%ld",objects.count);
       for(NSManagedObejct * mo in objects)//mo就是一个托管对象
           [mo deleteObject:mo];
       
   
   [context save:nil];//真正删除


-(IBAction)update:(UIButton *)sender
   AppDelegate * app=[UIApplication shareApplication].delegate; 
   NSManagedObjectContext * context=app.manageObjectContext;
   NSEnttityDescriptiotn * entity=[NSEntityDescription entityForName:@"Student" inManageObjectContext:context];
   NSFetchRequest * request=[[NSFetchRequest alloc]init];
   [request setEntity:entity];
   NSString * pred=[NSpredicate predicateWIthFormat:@"(age=%d)",22];
   [request setPredicate:pred];
   
   NSError * error=nil;
   NSArray * objects=[context executeFetchRequest:request error:&error];
   if(objects)//查询成功
       NSLog(@"%ld",objects.count);
       for(NSManagedObejct * mo in objects)//mo就是一个托管对象
           [mo setValue:[NSNumber numberWithInt:44] forKey:@"age"];//修改年龄
       
   
   [context save:nil];

企业中使用CoreData框架技术的只是少部分。但这并没有使用第三方组件来的更快一些。更多使用fastq技术

56章

登录注册

数据库应用网络登录和注册。创建单视图应用程序。

点击return关闭键盘:

点击视图关闭键盘:


@interface ViewController :UIViewController

    BOOL isRember;

//创建输出口和动作
@property (weak,nonatomic)IBOutlet UITextFeld * unameText;
@property (weak,nonatomic)IBOutlet UITextFeld * upassText;
@property (weak,nonatomic)IBOutlet UIButton * remButton;
-(IBAction)remTap:(UIButton *)sender;
@property (weak,nonatomic)IBOutlet UIButton * loginButton;//点击登录之后变灰
-(IBAction)loginTap:(UIButton *)sender;
@property (weak,nonatomic)IBOutlet UIButton * registButton;
-(IBAction)registTap:(UIButton *)sender;

-(IBAction)closeKeyboar:(UITextField *)sender;//两个文本框的关闭键盘动作都指向这个
-(IBAction)closeKB:(id)sender;

//ViewController.m
#import <sqlite3.h>
#import "MFUtil.h"
#import "MFDatabase.h"
-(void)viewDidLoad
    [super viewDidLoad];
    isRember=NO;
    
    if(![MFDatabase openDatabase:@"user.sqlite"]||![MFDatabase execSql:@"create table if not exists t_user(uname text not null,upass text not null)"])
        self.view.userInteractionEnabled=NO;
    
 
    NSString * uname=[[NSUserDefaults standardUserDefaults]objectForKey:@"USERNAME"];
    NSString * upass=[[NSUserDefaults standardUserDefaults]objectForKey:@"USERPASS"];
    if(uname.length>0&&upass.length>0)
        isRember=YES;
        [self.remButon setBackgroundImage:[UIImage imageNamed:@"check.png"]forState:UIControlStateNormal];
        self.unameText.text=uname;
        self.upassText.text=upass;
    
        


-(IBAction)remTap:(UIButton *)sender
    if(isRember==NO)//点击切换状态
      [sender setBackgroundImage:[UIImage imageNamed:@"check.png"]forState:UIControlStateNormal];
      isRember=YES;
    
    else
      [sender setBackgroundImage:[UIImage imageNamed:@"nocheck.png"]forState:UIControlStateNormal];
      isRember=NO;
    


-(void)lockView:(BOOL *)_lock andShowTitle:(NSString *)_str andSender:(UIButton *)_sender
    [self closeKB:nil];
    [_sender setTitle:_str forState:UIControlStateNormal];
    self.view.userInteractionEnabled=_lock;//封锁或者解锁

-(IBAction)loginTap:(UIButton *)sender
     NSString * uname=self.unameText.text;
     NSString * upass=self.upassText.text;
     uname=[MFUitil trim:uname];
     upass=[MFUitil trim:upass];
     NSLog(@"name=%@,pass=%@",uname,upass);
     if([uname isEqualToString@""])
        /*
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"账号不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];
        */
        [MFUtil alert:@"账号不能为空"];
        self.unameText.text=@"";
        [self.unameText becomeFirstResponder];
        return;
    
    if([upass isEqualToString@""])
        /*
        UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"密码不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"密码不能为空"];
        self.upassText.text=@"";
        [self.upassText becomeFirstResponder];
        return;
    
    /*
    [self closeKB:nil];
    [self.loginButton setTitle:@"正在登录..." forState:UIControlStateNormal];
    self.view.userInteractionEnabled=NO;*/
    [self lockView:NO andShowTitle:@"正在登录..." andSender:self.loginButton];
    
    /*char * path=NSHomeDirectory();
    path=[path stringByAppendingPathComponetn:@"user.sqlite"];
    NSLog(@"path=%@",path);
    sqlite3 * db;
    int result=sqlite3_open([path UTF8String],&db);
    if(result!=SQLITE_OK)
        NSLog(@"数据库打开失败....");
        sqlite3_close(db);
        return;
    */
    
    
    //检查用户是否存在,查询sql
    
    char *  sql="select * from t_user where uname=? and upass=?";
    sqlite3_stmt * stmt;
    result=sqlite3_prapare_v2(db,sql,-1,&stmt,NULL);
    
    if(result!=SQLITE_OK)
        NSLog(@"陈述绑定失败");
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return;
    
    
    if(sqlite3_bind_text(stmt,1,[uname UTF8String],-1,NULL)!=SQLITE_OK)
        NSLog(@"uname绑定失败");
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return;
    
    if(sqlite3_bind_text(stmt,2,[upass UTF8String],-1,NULL)!=SQLITE_OK)
        NSLog(@"upass绑定失败");
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return;
    
    
    if(sqlite3_step(stmt)==SQLITE_ROW)//如果有用户信息
        /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"登录成功" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"登录成功"];
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        /*
        self.view.userInteractionEnabled=YES;
        [self.loginButton setTitlte:@"登录" forState:UIControlStateNormal];*/
        [self lockView:YES andShowTitle:@"登录" andSender:self.loginButton];
        
        //进入程序主界面
        if(isRember)
           [[NSUserDefaults stanardUserDefaults] setObject:uname forKey:@"USERNAME"];
           [[NSUserDefaults stanardUserDefaults] setObject:upass forKey:@"USERPASS"];
        
        else
           [[NSUserDefaults stanardUserDefaults] removeObject:uname forKey:@"USERNAME"];
           [[NSUserDefaults stanardUserDefaults] removeObject:upass forKey:@"USERPASS"];
        
        
        return;
    
    
     /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"登录失败" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
     [alert show];*/
    [MFUtil alert:@"登录失败"];
    sqlite3_finalize(stmt);
    sqlite3_close(db);
    /*
    self.view.userInteractionEnabled=YES;
    [self.loginButton setTitlte:@"登录" forState:UIControlStateNormal];*/
    [self lockView:YES andShowTitle:@"登录" andSender:self.loginButton];

-(IBAction)registTap:(UIButton *)sender
    NSString * uname=self.unameText.text;
    NSString * upass=self.upassText.text;
    //数据有效性验证
    //剔除前后空格
    uname=[MFUitil trim:uname];
    upass=[MFUitil trim:upass];
    NSLog(@"name=%@,pass=%@",uname,upass);
    if([uname isEqualToString@""])
        /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"账号不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"账号不能为空"];
        self.unameText.text=@"";
        [self.unameText becomeFirstResponder];//重新获得焦点
        return;
    
    if([upass isEqualToString@""])
        /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"密码不能为空" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"密码不能为空"];
        self.upassText.text=@"";
        [self.upassText becomeFirstResponder];
        return;
    
    
    /*
    [self closeKB:nil];
    [self.registButton setTitle:@"正在注册..." forState:UIControlStateNormal];
    //self.registButton.enabled=NO;//封锁注册按钮,避免重复注册,按道理应该封锁整个界面
    self.view.userInteractionEnabled=NO;//不允许视图与用户进行交互 */
    [self lockView:NO andShowTitle:@"正在注册..." andSender:self.registButton];
    
    //检查用户是否存在,链接数据库
    //Build 增加数据库文件,选择动态链接库libsqlite3.dylib,导入头文件
    /*
    char * path=NSHomeDirectory();
    path=[path stringByAppendingPathComponetn:@"user.sqlite"];
    NSLog(@"path=%@",path);
    sqlite3 * db;
    int result=sqlite3_open([path UTF8String],&db);//打开数据库
    if(result!=SQLITE_OK)
        NSLog(@"数据库打开失败....");
        sqlite3_close(db);
        return;
    
    

    char * sql="create table if not exists t_user(uname text not null,upass text not null)";//创建用户表
    char * error;
    restult=sqlite3_exec(db,sql,NULL,NULL,&error);//运行sql
    if(result!=SQLITE_OK)
        NSLog(@"创建用户表失败....,error=%@",error);
        sqlite3_close(db);
        return;
    */
    
    //检查用户是否存在,查询sql
    char * sql="select * from t_user where uname=?";
    sqlite3_stmt * stmt;
    int result=sqlite3_prapare_v2([MFDatabase getDb],sql,-1,&stmt,NULL);
    
    if(result!=SQLITE_OK)
        NSLog(@"陈述绑定失败");
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        return;
    
    
    if(sqlite3_bind_text(stmt,1,[uname UTF8String],-1,NULL)!=SQLITE_OK)
        NSLog(@"uname绑定失败");
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        return;
    
    
    if(sqlite3_step(stmt)==SQLITE_ROW)
        /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"用户名已存在" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"用户名已存在"];
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        /*
        self.view.userInteractionEnabled=YES;//视图解锁
        [self.registButton setTitlte:@"注册" forState:UIControlStateNormal];*/
        [self lockView:YES andShowTitle:@"注册" andSender:self.registButton];
        return;
    
    
    //增加用户sql
    sql="inset into t_user valuse(?,?)";
    sqlite3_finalize(stmt);//先释放前面查询的陈述
    result=sqlite3_prapare_v2(db,sql,-1,&stmt,NULL);
    
    if(result!=SQLITE_OK)
        NSLog(@"陈述绑定失败");
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        return;
    
    
    if(sqlite3_bind_text(stmt,1,[uname UTF8String],-1,NULL)!=SQLITE_OK)
        NSLog(@"uname绑定失败");
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        return;
    
    if(sqlite3_bind_text(stmt,2,[upass UTF8String],-1,NULL)!=SQLITE_OK)
        NSLog(@"upass绑定失败");
        sqlite3_finalize(stmt);
        //sqlite3_close(db);
        return;
    
    
    if(sqlite3_step(stmt)!=SQLITE_DONE)//预处理失败
        /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"注册失败" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
        [alert show];*/
        [MFUtil alert:@"注册失败"];
        sqlite3_finalize(stmt); 
        //sqlite3_close(db);
        return;
    
    
    /*UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"友情提示"message:@"注册成功" delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
    [alert show];*/
    [MFUtil alert:@"注册成功"];
    sqlite3_finalize(stmt); 
    //sqlite3_close(db);
    /*
    self.view.userInteractionEnabled=YES;//解锁视图
    [self.registButton setTitlte:@"注册" forState:UIControlStateNormal];*/
    [self lockView:YES andShowTitle:@"注册" andSender:self.registButton];


-(IBAction)closeKeyboar:(UITextField *)sender


-(IBAction)closeKB:(id)sender
    //让两个文本框失去焦点
    [self.unameText resignFirstResponder];//resign重新设置
    [self.upassText resignFirstResponder];


@interface
+(void)alert:(NSString *)msg;
+(NSString *)trim:(NSString *)_str;
//MFUtil.m
#import <UIKit/UIKit.h>
+(void)alert:(NSString *)msg
      UIAlertView * av=[[UIAlertView alloc]initWithTitle:@"友情提示"message:msg delegate:nil cancelButtonTitle:@"知道" otherButtonTitles:nil,nil];
      [av show];

+(NSString *)trim:(NSString *)_str
    return [_str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

#import "sqlite3.h"
@interface
+(BOOL)openDatabase:(NSString *)_name;
+(BOOL)execSql:(NSString *)_sql;
+(sqlite3 *)getDb;
//MFDatabase.m
#import "MFUtil.h"
static sqlite3 * db=NULL;
+(BOOL)openDatabase:(NSString *)_name
    NSString * path=NSHomeDirectory();
    path=[path stringByAppendingPathComponent:_name];
    NSLog(@"path=%@",path);
    int result=sqlite3_open([path UTF8String],&db);
    if(result!=SQLITE_OK)
        NSLog(@"数据库打开失败....");
        sqlite3_close(db);
        return NO;
    
    return YES;

+(BOOL)execSql:(NSString *)_sql
    char * error;
    int restult=sqlite3_exec(db,[_sql UTF8String],NULL,NULL,&error);//运行sql
    if(result!=SQLITE_OK)
        NSLog(@"%@运行失败,error=%@",_sql,error);
        //sqlite3_close(db);
        return;
    
    return YES;

+(sqlite3 *)getDb
    return db;

57章

web

iOS数据库网络之Web介绍。mac系统自带Apache服务器。

# 启动localhost服务
sudo apachectl start
# /资源库/WebServer/Documents/index.html.en 
# 网页文件:静态htm html  动态asp aspx jsp php

html

<!-- index.html -->
<html>
    <head>
         <!-- 指定字符集否则汉字乱码 -->
         <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
		<title>hello</title>
    </head>
    <body>
<!-- 文字,图片,超级链接,表格,多媒体,表单对象,javascript -->
        &nbsp
        <br>
        <!-- 建议使用单引号 -->
        <front size='8' color='red'></front>
        <img src='logo.png' width='100' heigth='200'>
        <a href='b.html'>跳转</a>
        <table border='1' align='center'>
            <tr>
                <td>111</td>
                <td>222</td>
                <td>333</td>
            </tr>
            <tr>
                <td>111</td>
                <td>222</td>
                <td>333</td>
            </tr>
        </table>
        <input type='text'><input type='button' value='确定' onclick='ontap();'>
        <input type='radio'><input type='checkbox'>
        
        <center>居中显示</center>
        <hr>
        <form action="login.php" method="post">
        <table align='center' border='1' width='300'>
            <tr>
                <td>账号</td>
                <td><input type='text' maxlength='10' name="uname"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type='password' maxlength='10' name="upass"></td>
            </tr>
            <tr>
                <td><input type='submit' value='登录' name="action"></td>
                <td><input type='submit' value='注册' name="action"></td>
            </tr>
        </table>        
        </form>
        
    </body>
</html>
<script>
    function ontap()
        alert("hello");
    
</script>
//login.php
<html>
    <head>
    	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
   		<title></title>
    </head>
    <body>
    	<?
    	 	echo 12*12;//输出语句
		    echo "你好";
			$a=123;//定义变量
			echo $a;
			if($a>0) echo "正数";
             else echo "负数";
			for($b=1;$b<4;$b++) echo $b;
    	?>
         <script>
             document.write("hello");
         </script>
    </body>
</html>

开启浏览器解析php文件。/ect/apache2/httpd.conf/。

终端重启apache的web服务。sudo apachectl stop。

php区别于前面的静态页面。 动态页面里面的代码在服务器端运行。


mysql

iOS可以嵌入sqlite3,但是web端是不能运用的,web应该使用mysql。安装mysql数据库。安装mysql服务:

启动mysql的服务:

安装后地址:/usr/local/mysql/。安装数据库管理工具。

打开管理工具链接数据库。修改密码:

update `user` set Password=PASSWORD("1234") where User="root"
<html>
    <head>
    	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
   		<title></title>
    </head>
    <body>
//db.php 在php中操作数据库 1、链接和MySql和数据库,2、对数据库进行操作,3、关闭数据库
        <?
        echo "hello!";
        $conn=mysql_connetc("127.0.0.1","root","1234");
        if(!Swift 3.1 Coredata 按字母升序排序,但保留以数字开头的记录

iOS中数组的倒序升序降序

量化交易单因子有效性分析目的

iOS之数组的排序(升序降序及乱序)

iOS学习03

iOS学习03