iphone 应用学习所有代码

第十七天:网络连接


//
//  ShowViewController.m
//  ASILastDay
//
//  Created by Student on 8/22/14.
//  Copyright (c) 2014 Student. All rights reserved.
//


#import "ShowViewController.h"
#import "ASIHTTPRequest.h"
#import "JSON.h"
#import "ASIFormDataRequest.h"
#import "MBProgressHUD.h"
#import "UIDevice-Reachability.h"


#define URL  @"http://210.51.165.101/1qaz2wsx3edc/MInterface/BLogin.php?v_mid=10001&v_uname=Xiaxind1&v_pass=123456&v_signMsg=5302201A16F016C0D0697B470263D452"






#define ZHUCEURL @"http://192.168.10.81:8080/service/registeruser"


#define DENGLUURL @"http://192.168.10.81:8080/service/userlogin"


#define WENZISHANGCHUANURL @"http://192.168.10.81:8080/service/uploadusernote?user_name=caoyang"


#define WENZIBIJIXIAZAIURL @"http://192.168.10.81:8080/service/downloadusernote?user_name=caoyang"


#define GETIMAGEID @"http://192.168.10.81:8080/service/startimagenotesync?user_name=caoyang"


#define SHANGCHUANTUPIANBIJIURL @"http://192.168.10.81:8080/service/uploaduserimagenote?user_name=caoyang"


#define XIAZAITUPIANBIJI @"http://192.168.10.81:8080/service/downloaduserimagenote?user_name=caoyang"


@interface ShowViewController ()<ASIHTTPRequestDelegate>
{
    NSOperationQueue* queue;
    NSString* strID;
}
@end


@implementation ShowViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self ASI1]; //调用同步请求方法
    //[self ASI2]; //调用异步请求方法
    //[self ASI3]; //队列请求方法
    //[self postASI4]; //提交表单
}
//同步读取
-(void)ASI1
{
    
    
    //下载图片笔记
    MBProgressHUD *mbp = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].delegate window] animated:YES];
    mbp.center=CGPointMake(160, 200);
    mbp.labelText = @"发送中";
    //表单 与 post
    NSURL *url=[NSURL URLWithString:XIAZAITUPIANBIJI];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setTag:1005];
    
    [request setDelegate:self];
    [request startAsynchronous];
     
    
    /*
     
     
     //http与get
     /*
     同步上传方法
     //直接上传
    NSURL *url = [NSURL URLWithString:GETIMAGEID];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
     */
    
     /*
      异步上传方法  有一个代理
     NSURL *url = [NSURL URLWithString:GETIMAGEID];
     ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
     [request startSynchronous];
    NSError *error = [request error];
    if (!error)
    {
        
        //上传图片笔记
        
        NSRange str = [[request responseString] rangeOfString:@"<sync_id>"];
        NSRange str1 = [[request responseString] rangeOfString:@"</sync_id>"];
        if(str.location!=NSNotFound)
        {
            strID = [[request responseString] substringWithRange:NSMakeRange(str.location+9,str1.location-str.location-9)];
            NSLog(@"...%@",strID);
            
            
            //上传图片笔记
            MBProgressHUD *mbp = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].delegate window] animated:YES];
            mbp.center=CGPointMake(160, 200);
            mbp.labelText = @"发送中";
            
            NSURL *url=[NSURL URLWithString:SHANGCHUANTUPIANBIJIURL];
            ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
            [request setRequestMethod:@"POST"];
            [request setTag:1002];
            
            [request setPostValue:strID forKey:@"sync_id"];//回调值
            [request setPostValue:@"1" forKey:@"image_id"];//图片名字唯一标示
            [request setPostValue:@"asdfasdf" forKey:@"image_note"];
            
            NSString* strPath = [[NSBundle mainBundle]pathForResource:@"AA" ofType:@"png"];
            [request setFile:strPath forKey:@"file"];
            
            [request setDelegate:self];
            [request startAsynchronous];
        }
         
        
        //NSString *response = [request responseString];
        //NSDictionary * jsonDic = (NSDictionary*)[response JSONValue];
        //NSString* str = [jsonDic objectForKey:@"v_mid"];
        //NSLog(@"...%@",str);
    }
    */
    
    
     
    
    
    //登录
    /*
    MBProgressHUD *mbp = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].delegate window] animated:YES];
    mbp.center=CGPointMake(160, 200);
    mbp.labelText = @"发送中";
    
    NSURL *url=[NSURL URLWithString:DENGLUURL];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setTag:1002];
    //注册
    [request setPostValue:@"caoyang" forKey:@"user_name"];
    [request setPostValue:@"password" forKey:@"user_password"];
    
    [request setDelegate:self];
    [request startAsynchronous];
     */
    
    //上传文字笔记
    /*
    MBProgressHUD *mbp = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].delegate window] animated:YES];
    mbp.center=CGPointMake(160, 200);
    mbp.labelText = @"发送中";
    
    NSURL *url=[NSURL URLWithString:WENZISHANGCHUANURL];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setTag:1002];
   
    NSMutableString* stringData = [NSMutableString stringWithString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"];
    [stringData appendString:@"asdf"];
    [stringData appendString:@"\t\t<item>\n"];
    [stringData appendString:@"\t\t\t<title>"];
    [stringData appendString:@"1234567890"];
    [stringData appendString:@"</title>"];
    
    
    NSMutableData* xmlData = [[stringData dataUsingEncoding:NSUTF8StringEncoding]mutableCopy];
    [request setPostBody:xmlData];
    
    [request setDelegate:self];
    [request startAsynchronous];
     */
    
    //下载文字笔记
    /*
    MBProgressHUD *mbp = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].delegate window] animated:YES];
    mbp.center=CGPointMake(160, 200);
    mbp.labelText = @"发送中";
    
    NSURL *url=[NSURL URLWithString:WENZIBIJIXIAZAIURL];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setTag:1002];
    
    [request setDelegate:self];
    [request startAsynchronous];
     */
    
}
//异步读取
-(void)ASI2
{
    
    /*
    MBProgressHUD *mbp = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].delegate window] animated:YES];
    mbp.center=CGPointMake(150, 200);
    mbp.labelText = @"  请求中...  ";
    //for(int i=0;i<50;i++)
    //{
    NSURL *url = [NSURL URLWithString:URL];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request setTimeOutSeconds:20.0f];
    [request setShouldContinueWhenAppEntersBackground:YES ];//后台请求
    [request setTag:1001];
    [request startAsynchronous];
    //}*/
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
    [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication].delegate window] animated:YES];
    if(![UIDevice networkAvailable])
    {
        NSLog(@"网络不可用!");
    }
    else
    {
        if(request.tag==1001)
        {
            // 当以文本形式读取返回内容时用这个方法
            NSString *responseString = [request responseString];
            NSDictionary * jsonDic = (NSDictionary*)[responseString JSONValue];
            NSString* str = [jsonDic objectForKey:@"v_mid"];
            NSLog(@"...%@",str);
            
            // 当以二进制形式读取返回内容时用这个方法
            //NSData *responseData = [request responseData];
        }
        else if(request.tag==1002)
        {
            NSLog(@"....%@",[request responseString]);
        }
        else if(request.tag==1005)
        {
            NSLog(@"....%@",[request responseString]);
        }
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication].delegate window] animated:YES];
    NSError* error = [request error];
    NSLog(@"%@",error);
}
//队列请求 一个一个的下载或上传
-(void)ASI3
{
    queue = [[[NSOperationQueue alloc]init]autorelease];
    [queue setMaxConcurrentOperationCount:1];
    for(int i=0;i<10;i++)
    {
        NSURL *url = [NSURL URLWithString:URL];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        [request setTag:1005];
        [request setDelegate:self];
        [request setDidFinishSelector:@selector(requestDone:)];
        [request setDidFailSelector:@selector(requestWentWrong:)];
        [queue addOperation:request];
        [request cancel];
    }
}
-(void)requestDone:(ASIHTTPRequest*)request
{
    NSString *responseString = [request responseString];
    NSDictionary * jsonDic = (NSDictionary*)[responseString JSONValue];
    NSString* str = [jsonDic objectForKey:@"v_mid"];
    NSLog(@"...%@",str);
}
-(void)requestWentWrong:(ASIHTTPRequest*)request
{
    NSError* error = [request error];
    NSLog(@">>>>>%@",error);
}
//注册
-(void)postASI4
{
    MBProgressHUD *mbp = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].delegate window] animated:YES];
    mbp.center=CGPointMake(160, 200);
    mbp.labelText = @"发送中";
    
    NSURL *url=[NSURL URLWithString:ZHUCEURL];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setTag:1002];
    //注册
    [request setPostValue:@"caoyang" forKey:@"user_name"];
    [request setPostValue:@"password" forKey:@"user_password"];
    /*
    //上传文件保存路径
    [request addFile:@"图片路径" withFileName:@"image.png" andContentType:@"png" forKey:@"myFile"];
    
    [request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];
    [request addData:@"把图片转换成data" withFileName:@"george.jpg" andContentType:@"image/jpeg"forKey:@"photos"];
    */
    [request setDelegate:self];
    [request startAsynchronous];
}






- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end


第十六天:
数据库的封装源码:
#import "AA.h"


@implementation AA


//打开数据库
+(void)OpenDB
{
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"MyData.db"];
    
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    delegate.dbs = [FMDatabase databaseWithPath:writableDBPath];     //创建并打开FMDB
    if (![delegate.dbs open])
    {
        NSLog(@"Could not open db.");
    }
    else
    {
        NSLog(@"Can open db.");
    }
}
//建表
+(void)creatTable
{
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    [delegate.dbs executeUpdate:@"CREATE TABLE Person (name , passWord)"];
    //    [dbs executeUpdate:@"CREATE TABLE  Per(name, passWord)"];
    if([delegate.dbs hadError])
    {
        NSLog(@" 表创建失败");
    }
    else
    {
        NSLog(@"表创建成功");
    }
}


//查询所有数据
+(void)Select
{
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    FMResultSet *rs = [delegate.dbs executeQuery:@"SELECT * FROM Person"];
    while ([rs next])
    {
        NSString *name = [rs stringForColumn:@"name"];
        NSString* passWord = [rs stringForColumn:@"passWord"];
        
        NSLog(@"name = %@ , PassWors = %@",name,passWord);
    }
    [rs close];
}


//往表中插入数据
+(void)InsertName:(NSString*)name andPassWord:(NSString*)passWord
{
     AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    [delegate.dbs executeUpdate:@"INSERT INTO Person (name,passWord) VALUES ( ? , ? )",name,passWord];
    if ([delegate.dbs hadError])
    {
        NSLog(@"Err: %@", [delegate.dbs lastErrorMessage]);
    }
    else
    {
        NSLog(@"插入数据成功");
    }
}


//修改数据 更新
+(void)UpdateName:(NSString*)name WithPassWord:(NSString*)passWord
{
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
     [delegate.dbs executeUpdate:@"UPDATE Person SET passWord = ? WHERE name = ?",passWord,name];
}


//删除部分数据
+(void)DeleteUserWithName:(NSString*)name
{
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    [delegate.dbs executeUpdate:@"DELETE FROM Person Where name = ?",name];
}


//删除所有数据  删除表
+(void)DeleteAllUser
{
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
//    NSString* sqlstr = [NSString stringWithFormat:@"delete from Person"];  //删除所有数据,表还存在
    NSString *sqlstr = [NSString stringWithFormat:@"DROP TABLE Person"];  //删除表
    if (![delegate.dbs executeUpdate:sqlstr])
    {
        NSLog(@"Delete table error!");
    }
    else
    {
        NSLog(@" SUCESS  !!");
    }
}


//关闭数据库
+(void)CloseDB
{
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    [delegate.dbs close];
}
@end


第十五天
(1)socket(客户端)
#import <UIKit/UIKit.h>
//#import <CFNetwork/CFNetwork.h>
#import "AsyncSocket.h"


#define SRV_CONNECT_FAIT 0
#define SRV_CONNECT_SUC 1
#define SRV_CONNECTED 2
//#define HOST_IP @"192.168.4.115"
#define HOST_IP @"192.168.4.117"


#define HOST_POST 8080


@interface SocketViewController : UIViewController<AsyncSocketDelegate>
{
    
}
@property(nonatomic,strong)AsyncSocket *client;


@end




#import "SocketViewController.h"




@interface SocketViewController ()


@end


@implementation SocketViewController
@synthesize client;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
[self connectServe:HOST_IP port:HOST_POST];
    
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(send) userInfo:nil repeats:YES];
    
}
//1.调用链接服务器  已经成功了
-(int)connectServe:(NSString *)hostIP port:(int)hostport
{
    NSLog(@"connectServe:(NSString *)hostIP port:(int)hostport");
    if(!client)
    {
        //self这个参数是必须得
        client=[[AsyncSocket alloc]initWithDelegate:self];
        NSError *error=nil;
       
        if([client connectToHost:hostIP onPort:hostport error:&error])
        {
            NSLog(@"成功!");
            return 1;
        }
        
        else
        {
            NSLog(@"%ld %@",(long)[error code],[error localizedDescription]);
            return SRV_CONNECT_FAIT;
        }
        //if([client connectedHost])
    }
    
    
    else
    {
        [client readDataWithTimeout:-1 tag:0];
        return SRV_CONNECTED;
    }
}


//2、发送send
-(void)send
{
    NSLog(@"send");
    if(!client){
        [self showMessage:@"sorry client faulat"];
    }else{
        NSString *inputMsgStr=@"ddd";
        NSString *content=[inputMsgStr stringByAppendingString:@"\r\n"];
        NSLog(@"%@",content);
        NSData *data=[content dataUsingEncoding:NSUTF8StringEncoding];
        [client writeData:data withTimeout:-1 tag:3];
    }
}


- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(@"willDisconnectWithError");
    NSLog(@"error");
}




- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    NSString *msg=@"sorry this connect is fault";
     [self showMessage:msg];
    client=nil;
    
}
-(void)showMessage:(NSString *)s
{
    UIAlertView *a=[[UIAlertView alloc]initWithTitle:@"提示" message:s delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [a show];
}


- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    [self showMessage:[NSString stringWithFormat:@"连接成功\n %@ %d",host,port]];
    //继续监听
    [client readDataWithTimeout:-1 tag:4];
}
//当socket已完成所要求的数据读入内存时调用,有错误不调用
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *astr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"receiver data is-----%@",astr);
    [astr release];
    //继续监听,递归调用
    [client readDataWithTimeout:-1 tag:5];
}
(2)服务器端
#import <Cocoa/Cocoa.h>
#import "AsyncSocket.h"
#define HOST_CLIENT_PORT 8080


@interface AppDelegate : NSObject <NSApplicationDelegate,AsyncSocketDelegate>
{
    AsyncSocket *socket;
    AsyncSocket *acceptSocket;
}


@property (assign) IBOutlet NSWindow *window;
@property(assign) NSText *clientMessage;
@property(assign) NSText *readText;


@end




- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    socket=[[AsyncSocket alloc]initWithDelegate:self];
    NSError *error=nil;
    if([socket acceptOnPort:HOST_CLIENT_PORT error:&error])
    {
        NSLog(@"accept ok!");
    }
    else
    {
        NSLog(@"fault!");
        NSLog(@"%@",error);
        return;
    }
    acceptSocket=[[AsyncSocket alloc]initWithDelegate:self];
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(AAA) userInfo:nil repeats:YES];
}


-(void)AAA
{
    NSData *acceptData=[@"没问题哈  嘘嘘哥!" dataUsingEncoding:NSUTF8StringEncoding];
    [acceptSocket writeData:acceptData withTimeout:-1 tag:0];
}


//当产生一个socket去处理连接时调用 次方法会返回
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
{
    NSLog(@"new socket!");
    acceptSocket=[newSocket retain];
}


//开启监听,当socket链接成功后,正准备读和写得时候调用, host属性是IP一个地址,而不是一个DNS名称
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"客户端与服务器连接成功!");
    [acceptSocket readDataWithTimeout:-1 tag:1];
}


//连接成功,打开监听数据读取,如果不坚挺无法读取数据已经完成要求的数据读入内存时调用  如果错误不调用
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSLog(@"kefjwejfewfjeijfiejr,%lu",tag);
    NSString *msg=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
   // NSLog(@"%@",[@"client:" stringByAppendingString:@"%@",msg]);
    NSLog(@"%@",[@"client:" stringByAppendingFormat:@"%@",msg]);
    [acceptSocket readDataWithTimeout:-1 tag:2];
}


- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"didWriteDataWithTag:%lu",tag);
    NSLog(@"thread(%@),onsocket:%p didWriteDataWithTag:%ld",[[NSThread currentThread] name],sock,tag);
}
第十四天
(1)网页下载一:
- (void)viewDidLoad
{
    [super viewDidLoad];
    imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
    [self.view addSubview:imageview];
    
    NSThread *thread= [[NSThread alloc]initWithTarget:self selector:@selector(downIconImage:) object:KURL];
    [thread start];


}


-(void)downIconImage:(NSString *)url
{
    NSData *data=[[NSData  alloc]initWithContentsOfURL:[NSURL URLWithString:url]];
    UIImage *img=[[UIImage alloc]initWithData:data];
    if(img==nil)
    {
        NSLog(@"下载失败!");
    }
    else
    {
        [self performSelectorOnMainThread:@selector(updateUI:) withObject:img waitUntilDone:YES];
    }
}


-(void)updateUI:(UIImage *)image
{
    imageview.image=image;
}


(2)多线程
#import <UIKit/UIKit.h>


@interface AAViewController : UIViewController
{
    int tickets;
    int count;
    NSThread *thread1;
    NSThread *thread2;
    NSThread *thread3;
    NSCondition *condition;//锁
    NSLock *lock1;//锁
}


@end




- (void)viewDidLoad
{
    [super viewDidLoad];
    tickets=100;
    count=0;
    
    
    lock1=[[NSLock alloc]init];
    condition=[[NSCondition alloc]init];
    
    thread1=[[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
    [thread1 setName:@"thread-1"];
    [thread1 start];
    
    thread2=[[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
    [thread2 setName:@"thread-2"];
    [thread2 start];
 
    
    thread3=[[NSThread alloc]initWithTarget:self selector:@selector(run3) object:nil];
    [thread3 setName:@"thread-3"];
    [thread3 start];
// Do any additional setup after loading the view.
}


-(void)run
{
    while(TRUE)
    {
        [condition lock];
        [condition wait];
        
        [lock1 lock];
        if(tickets>=0)
        {
            [NSThread sleepForTimeInterval:0.09];
            count=100-tickets;
            NSLog(@"当前%d  售出%d  县城名:%@",tickets,count,[[NSThread currentThread]name]);
            tickets--;
        }
        else
        {
            break;
        }
        [lock1 unlock];
        [condition unlock];
    }
}


-(void)run3
{
    while(YES)
    {
        [condition lock];
        [NSThread sleepForTimeInterval:2];
        [condition signal];
        [condition unlock];
    }
}


(3)多线程下载
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
    [self.view addSubview:imageview];
    
//    NSThread *thread= [[NSThread alloc]initWithTarget:self selector:@selector(downIconImage:) object:KURL];
//    [thread start];
    
    NSInvocationOperation *operation=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(downIconImage:) object:KURL];
    NSOperationQueue *queue= [[NSOperationQueue alloc]init];
    
    [queue addOperation:operation];
    
// Do any additional setup after loading the view.
}


-(void)downIconImage:(NSString *)url
{
    NSData *data=[[NSData  alloc]initWithContentsOfURL:[NSURL URLWithString:url]];
    UIImage *img=[[UIImage alloc]initWithData:data];
    if(img==nil)
    {
        NSLog(@"下载失败!");
    }
    else
    {
        [self performSelectorOnMainThread:@selector(updateUI:) withObject:img waitUntilDone:YES];
        
    }
}


-(void)updateUI:(UIImage *)image
{
    imageview.image=image;
}


(4)多线程
- (void)viewDidLoad
{
    [super viewDidLoad];
    imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
    [self.view addSubview:imageview];
    
    /*
    //单任务
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        NSURL *url=[NSURL URLWithString:KURL];
        NSData *data=[[NSData  alloc]initWithContentsOfURL:url];
        UIImage *img=[[UIImage alloc]initWithData:data];
        
        if(data!=nil)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                imageview.image=img;
            });
        }
    });
     */
    
    /*
    //队列一
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    dispatch_group_t group=dispatch_group_create();
    
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:1];
        NSLog(@"group1");
        
    });
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:2];
        NSLog(@"group2");
        
    });
    dispatch_group_async(group, queue, ^{
        [NSThread sleepForTimeInterval:3];
        NSLog(@"group3");
        
    });
    //队列执行结束发出一个通知
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"update");
    });
    dispatch_release(group);
    */
    
    /*
    //队列二
    dispatch_queue_t queue=dispatch_queue_create("young",DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
    
        NSLog(@"dispath_asygn1");
    });
    dispatch_async(queue, ^{
        
        NSLog(@"dispath_asygn2");
    });
    dispatch_async(queue, ^{
        
        NSLog(@"dispath_asygn4");
    });
    dispatch_async(queue, ^{
        
        NSLog(@"dispath_asygn5");
    });
    dispatch_async(queue, ^{
        
        NSLog(@"dispath_asygn6");
    });
    
    //dispatch_barrier_async保证前面的先执行结束 保证dispath_asygn3后执行
    
    dispatch_barrier_async(queue, ^{
        NSLog(@"dispatch_barrier_async");
    });
    dispatch_async(queue, ^{
     NSLog(@"dispath_asygn3");
    });
    */


    //队列三  循环执行  相当于for
    dispatch_queue_t queue=dispatch_queue_create("young",DISPATCH_QUEUE_CONCURRENT);
    dispatch_apply(5, queue, ^(size_t  index){
        NSLog(@"ergergerg");
    });
    
    
}


第十三天
(1)KVO
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    datas=[[Waker alloc]initwithAge:20 andName:@"liming"];
    [datas addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
    
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(120, 200, 100, 35);
    btn.backgroundColor=[UIColor redColor];
    [btn setTitle:@"增加5穗" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnpressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    
    ageLabel=[[UILabel alloc]initWithFrame:CGRectMake(40, 150, 200, 35)];
    ageLabel.text=[NSString stringWithFormat:@"%@现在的年龄:%d",datas.name,datas.age];
    ageLabel.backgroundColor=[UIColor grayColor];
    [self.view addSubview:ageLabel];
    [ageLabel release];
// Do any additional setup after loading the view.
}


-(void)btnpressed:(id)sender
{
    datas.age +=5;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    ageLabel.text=[NSString stringWithFormat:@"%@现在的年龄:%d",datas.name,datas.age];
}


-(void)dealloc
{
    [super dealloc];
    [datas removeObserver:self forKeyPath:@"age"];
}


(2)本地推送
-(void)noti
{
    NSString *strTime=@"2014-08-21 14:57:50";
    NSDateFormatter *dateformator=[[NSDateFormatter alloc]init];
    [dateformator setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *destDate=[dateformator dateFromString:strTime];
    [dateformator release];
    //创建一个本地推送
    UILocalNotification *localNotification= [[UILocalNotification alloc]init];
    if(!localNotification)
    {
        return;
    }
    [arrays addObject:localNotification];
    localNotification.fireDate=destDate;
    localNotification.alertBody=@"本地通知";
    //提示
    localNotification.alertAction=@"view";
    //设置重复间隔
    localNotification.repeatInterval=NSDayCalendarUnit;
    //显示在icon上得红色数字
    localNotification.applicationIconBadgeNumber=[arrays count];
    
    
    //localNotification sound
    //localNotification.soundName=@"<#string#>"//不能超过30秒
    
    localNotification.soundName=UILocalNotificationDefaultSoundName;
    //schedule安排
    [[UIApplication sharedApplication]scheduleLocalNotification:localNotification];
    [localNotification release];
    
    //清空所有的提醒
}


第十二天   本地化
(1)
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    datas=[[Waker alloc]initwithAge:20 andName:@"liming"];
    [datas addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
    
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(120, 200, 100, 35);
    btn.backgroundColor=[UIColor redColor];
    [btn setTitle:@"增加5穗" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnpressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    
    ageLabel=[[UILabel alloc]initWithFrame:CGRectMake(40, 150, 200, 35)];
    ageLabel.text=[NSString stringWithFormat:@"%@现在的年龄:%d",datas.name,datas.age];
    ageLabel.backgroundColor=[UIColor grayColor];
    [self.view addSubview:ageLabel];
    [ageLabel release];
// Do any additional setup after loading the view.
}


-(void)btnpressed:(id)sender
{
    datas.age +=5;
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    ageLabel.text=[NSString stringWithFormat:@"%@现在的年龄:%d",datas.name,datas.age];
}


-(void)dealloc
{
    [super dealloc];
    [datas removeObserver:self forKeyPath:@"age"];
}
#import "ShowViewController.h"


@interface ShowViewController ()


@end


@implementation ShowViewController




- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString* strLabel = [NSString stringWithString:NSLocalizedString(@"welcome", nil)];
    NSLog(@"...%@",strLabel);
    
    NSString* strImage = [NSString stringWithString:NSLocalizedString(@"tupian", nil)];
    NSLog(@"...%@",strImage);
    
    UILabel* lala = [[UILabel alloc]init];
    lala.frame = CGRectMake(0, 0, 320, 40);
    [lala setText:strLabel];
    [self.view addSubview:lala];
    
    UIImageView* ima = [[UIImageView alloc]init];
    ima.frame = CGRectMake(0, 50, 100, 100);
    //[ima setImage:[UIImage imageNamed:strImage]];
    [ima setImage:[UIImage imageNamed:@"ICON.png"]];
    [self.view addSubview:ima];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end




(2)


#import "ShowViewController.h"


@interface ShowViewController ()<UIGestureRecognizerDelegate>
{
    UIImageView* imageM;
}
@end


@implementation ShowViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    imageM = [[UIImageView alloc]init];
    imageM.frame = CGRectMake(0, 0, 320, 460);
    [imageM setImage:[UIImage imageNamed:@"A.png"]];
    /*
     当视图对象的userInteractionEnabled设置为NO的时候,用户触发的事件,如触摸,键盘等,将会被该视图忽略(其他视图照常响应),并且该视图对象也会从事件响应队列中被移除。 当userInteractionEnabled设为YES时,则事件可以正常的传递给该视图对象。 userInteractionEnabled的属性默认值就是YES。
     ps:响应者链是能够响应事件的对象组成的链,事件在该链上传递,最终结果事件或被处理或被抛弃。所以一个对象在不在响应者链里是其能否响应事件的首要前提条件!
    */
    imageM.userInteractionEnabled = YES;
    [self.view addSubview:imageM];
     
    /*
    //1、创建手势实例,并连接方法handleTapGesture,点击手势
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapGesture:)];
    tapGesture.delegate = self;
    //允许几个手指
    tapGesture.numberOfTouchesRequired = 2;
    //设置手势点击数,双击:点2下
    tapGesture.numberOfTapsRequired=2;
    // imageView添加手势识别
    [self.view addGestureRecognizer:tapGesture];
    //释放内存
    [tapGesture release];
    */
    
    /*
    //2、手势为捏的姿势:按住option按钮配合鼠标来做这个动作在虚拟器上
    UIPinchGestureRecognizer *pinchGesture=[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(handlePinchGesture:)];
    [imageM addGestureRecognizer:pinchGesture];//imageView添加手势识别
    [pinchGesture release];
    */
     
    /*
    //3、旋转手势:按住option按钮配合鼠标来做这个动作在虚拟器上
    UIRotationGestureRecognizer *rotateGesture=[[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(handleRotateGesture:)];
    [imageM addGestureRecognizer:rotateGesture];
    [rotateGesture release];
    */
    
    /*
    //4、拖手势
    UIPanGestureRecognizer *panGesture=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePanGesture:)];
    [imageM addGestureRecognizer:panGesture];
    [panGesture release];
     */
    
    /*
    //5、划动手势
    //右划
    UISwipeGestureRecognizer *swipeRightGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGesture:)];
    swipeRightGesture.direction=UISwipeGestureRecognizerDirectionRight;
    [imageM addGestureRecognizer:swipeRightGesture];
    [swipeRightGesture release];
    
    //左划
    UISwipeGestureRecognizer *swipeLeftGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGesture:)];
    swipeLeftGesture.direction=UISwipeGestureRecognizerDirectionLeft;
    [imageM addGestureRecognizer:swipeLeftGesture];
    [swipeLeftGesture release];
    
    //上划
    UISwipeGestureRecognizer *swipeUpGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGesture:)];
    swipeUpGesture.direction=UISwipeGestureRecognizerDirectionUp;
    [imageM addGestureRecognizer:swipeUpGesture];
    [swipeUpGesture release];
    
    //下划
    UISwipeGestureRecognizer *swipeDownGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGesture:)];
    swipeDownGesture.direction=UISwipeGestureRecognizerDirectionDown;
    [imageM addGestureRecognizer:swipeDownGesture];
    [swipeDownGesture release];
    */
     
    
    //6、长按手势
    UILongPressGestureRecognizer *longpressGesutre=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongpressGesture:)];
    //长按时间为1秒
    longpressGesutre.minimumPressDuration=1;
    //所需手指数
    longpressGesutre.numberOfTouchesRequired=2;
    [imageM addGestureRecognizer:longpressGesutre];
    [longpressGesutre release];
}
/*
//双击屏幕时会调用此方法
-(void)handleTapGesture:(UIGestureRecognizer*)sender
{
    NSLog(@".....");
}
*/
 
/*
//捏的手势
-(void)handlePinchGesture:(UIGestureRecognizer*)sender
{
    NSLog(@",,,");
}
 */


/*
//旋转手势
-(void)handleRotateGesture:(UIGestureRecognizer*)sender
{
    NSLog(@"...");
}
 */


/*
//拖手势
-(void)handlePanGesture:(UIGestureRecognizer*)sender
{
    NSLog(@"//");
}
 */


/*
//划动手势
-(void)handleSwipeGesture:(UIGestureRecognizer*)sender
{
    //划动的方向
    UISwipeGestureRecognizerDirection direction=[(UISwipeGestureRecognizer*) sender direction];
    //判断是上下左右
    switch (direction)
    {
        case UISwipeGestureRecognizerDirectionUp:
            NSLog(@"up");
        break;
        case UISwipeGestureRecognizerDirectionDown:
            NSLog(@"down");
        break;
        case UISwipeGestureRecognizerDirectionLeft:
            NSLog(@"left");
        break;
        case UISwipeGestureRecognizerDirectionRight:
            NSLog(@"right");
        break;
        default:
        break;
    }
}
 */


//长按手势  
-(void)handleLongpressGesture:(UIGestureRecognizer*)sender
{
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        NSLog(@"Long press Ended");
    }
    else
    {
        NSLog(@"Long press detected.");
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
  
}
@end


第十一天:
(1)MapKit


#import "MapKitViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>




/*
 地图需要MapKit.framework
 定位需要CoreLocation.framework,它提供了一个CLLocationManager类来实现定位
 */
@interface MapKitViewController ()<CLLocationManagerDelegate>//定位代理
{
    MKMapView* mapView;
    CLLocationManager* manager;
    CLLocation* currentLocation;
}
@end


@implementation MapKitViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIButton* btnAnimation = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnAnimation.frame = CGRectMake(10, 10, 300, 40);
    [btnAnimation setTitle:@"Big" forState:UIControlStateNormal];
    [btnAnimation addTarget:self action:@selector(GoBig:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnAnimation];
    [btnAnimation release];
    
    UIButton* btnCamera = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnCamera.frame = CGRectMake(10, 60, 300, 40);
    [btnCamera setTitle:@"Small" forState:UIControlStateNormal];
    [btnCamera addTarget:self action:@selector(GoSmall:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnCamera];
    [btnCamera release];
    
    mapView = [[MKMapView alloc]init];
    mapView.frame = CGRectMake(0, 100, 320, 300);
    [self.view addSubview:mapView];
    
    manager = [[CLLocationManager alloc]init];
    manager.delegate = self; //设置代理
    [manager startUpdatingLocation]; //开始定位
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
  fromLocation:(CLLocation *)oldLocation
{
    currentLocation = newLocation;
    mapView.region = MKCoordinateRegionMake(newLocation.coordinate, MKCoordinateSpanMake(0.05, 0.05));
    mapView.showsUserLocation = YES;   //显示大头针
    [manager stopUpdatingLocation];    //更新一次后停止更新
}
-(void)GoBig:(id)sender
{
    MKCoordinateRegion region = mapView.region;
    //设置跨度
    region.span = MKCoordinateSpanMake(region.span.latitudeDelta*0.4,region.span.longitudeDelta*0.4);
    [mapView setRegion:region];
}
-(void)GoSmall:(id)sender
{
    MKCoordinateRegion region = mapView.region;
    //设置跨度
    region.span = MKCoordinateSpanMake(region.span.latitudeDelta*1.4,region.span.longitudeDelta*1.4);
    [mapView setRegion:region];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
(2)MutilTouch
#import "MutilTouchViewController.h"


@interface MutilTouchViewController ()
{
    UIImageView* imageM;
    double previousDistance;// 触摸点之间当前的距离
    double zoomFactor; //缩放因子
}


@end


@implementation MutilTouchViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    zoomFactor = 1; //初始化缩放因子
    
    imageM = [[UIImageView alloc]init];
    imageM.frame = CGRectMake(0, 0, 320, 300);
    [imageM setImage:[UIImage imageNamed:@"A.png"]];
    [self.view addSubview:imageM];
    [imageM release];


}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //判断当前触摸点为几个
if (event.allTouches.count)
    {
NSArray* touches = [event.allTouches allObjects];//获得屏幕上所有的UITouch对象
CGPoint p1 = [[touches objectAtIndex:0] locationInView:imageM];//获得笛卡尔坐标
CGPoint p2 = [[touches objectAtIndex:1] locationInView:imageM];
previousDistance = sqrt(pow(p1.x-p2.x, 2) + pow(p1.y-p2.y, 2));// 计算两点触摸点的距离
}
}


-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    //判断当前触摸点为几个
if (event.allTouches.count ==2)
    {
NSArray* touches = [event.allTouches allObjects];
        CGPoint p1 = [[touches objectAtIndex:0] locationInView:imageM];
        CGPoint p2 = [[touches objectAtIndex:1] locationInView:imageM];
double distance = sqrt(pow(p1.x-p2.x, 2) + pow(p1.y-p2.y, 2)); //计算两点之间的当前距离
zoomFactor += (distance - previousDistance)/previousDistance;//求缩放比
previousDistance = distance;
[self refreshView];
    }
}


-(void) refreshView
{
if(zoomFactor < 0.1) zoomFactor = 0.1; //控制缩放因子不过大或过小
    if(zoomFactor > 4 ) zoomFactor = 4;
CGRect newFrame = CGRectInset(imageM.frame,
                                  (imageM.frame.size.width - 100*zoomFactor)/2,
                                  (imageM.frame.size.height - 100*zoomFactor)/2);
    imageM.frame = newFrame;
    
}


-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
previousDistance = 0;//重置距离
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
(3)AudioView
@implementation AudioViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIButton* btnAnimation = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnAnimation.frame = CGRectMake(10, 10, 300, 40);
    [btnAnimation setTitle:@"play" forState:UIControlStateNormal];
    [btnAnimation addTarget:self action:@selector(GoPlay:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnAnimation];
    [btnAnimation release];
    
    UIButton* btnCamera = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnCamera.frame = CGRectMake(10, 60, 300, 40);
    [btnCamera setTitle:@"stop" forState:UIControlStateNormal];
    [btnCamera addTarget:self action:@selector(GoStop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnCamera];
    [btnCamera release];
    
    player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"caoyuan"  ofType:@"mp3"]] error:nil];
}
-(void)GoPlay:(id)sender
{
    [player play];
}
-(void)GoStop:(id)sender
{
    [player pause];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [player release];
    player = nil;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
(4)VideoView
#import "VideoViewController.h"
#import <MediaPlayer/MediaPlayer.h>      //包含头文件


@interface VideoViewController ()
{
    MPMoviePlayerController *player;     //声明播放器对象
    BOOL isPlay;                         //判断播放器当前的状态
}
@end


@implementation VideoViewController
/*
 MPMoviePlayerController和AVAudioPlayer有点类似,前者播放视频,后者播放音频,不过也有很大不同,MPMoviePlayerController可以直接通过远程的url初始化,而AVAudioPlayer则不可以,不过大体上感觉一样。格式支持MOV,MP4,M4V,3GP等。。。
 
 使用MPMoviePlayerController之前需要导入MediaPlayer.framework并且引入头文件
*/
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIButton* btnAnimation = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnAnimation.frame = CGRectMake(10, 10, 300, 40);
    [btnAnimation setTitle:@"play" forState:UIControlStateNormal];
    [btnAnimation addTarget:self action:@selector(GoPlay:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnAnimation];
    [btnAnimation release];
    
    UIButton* btnCamera = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnCamera.frame = CGRectMake(10, 60, 300, 40);
    [btnCamera setTitle:@"stop" forState:UIControlStateNormal];
    [btnCamera addTarget:self action:@selector(GoStop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnCamera];
    [btnCamera release];
    
    NSString *path = [[NSBundle mainBundle]pathForResource:@"test" ofType:@"m4v"];
    NSURL *url = [[NSURL alloc]initFileURLWithPath:path];
    player = [[MPMoviePlayerController alloc]initWithContentURL:url];
    [player.view setFrame:CGRectMake(0, 100, 320, 320)];
    [self.view addSubview:player.view];
}
-(void)GoPlay:(id)sender
{
    [player play];
}
-(void)GoStop:(id)sender
{
    [player pause];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [player release];
    player = nil;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
(5)Camera
#import "CameraViewController.h"


@interface CameraViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    UIImageView* imageM;
    UIImagePickerController *picker;
}
@end


@implementation CameraViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    UIButton* btnAnimation = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnAnimation.frame = CGRectMake(10, 10, 300, 40);
    [btnAnimation setTitle:@"相机" forState:UIControlStateNormal];
    [btnAnimation addTarget:self action:@selector(Goxiangji:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnAnimation];
    [btnAnimation release];
    
    UIButton* btnCamera = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnCamera.frame = CGRectMake(10, 60, 300, 40);
    [btnCamera setTitle:@"相册" forState:UIControlStateNormal];
    [btnCamera addTarget:self action:@selector(Goxiangce:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnCamera];
    [btnCamera release];
    
    imageM = [[UIImageView alloc]init];
    imageM.frame = CGRectMake(0, 100, 320, 300);
    [imageM setImage:[UIImage imageNamed:@"A.png"]];
    [self.view addSubview:imageM];
    [imageM release];
}


-(void)Goxiangji:(id)sender
{
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        picker = [[UIImagePickerController alloc]init];
        //设定为相机
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
        [picker release];
    }
    else
    {
        NSLog(@"not allow");
    }
}


-(void)Goxiangce:(id)sender
{
    
    picker = [[UIImagePickerController alloc]init];
    //设定相册
    picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate=self;
    [self presentViewController:picker animated:YES completion:nil];
    [picker release];
}
//UIImagePickerControllerDelegate的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
imageM.image = [info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
(6)Animation
#import "AnimationViewController.h"


@interface AnimationViewController ()
{
    UIImageView* imageM;
}
@end


@implementation AnimationViewController




- (void)viewDidLoad
{
    [super viewDidLoad];
    imageM = [[UIImageView alloc]init];
    imageM.frame = CGRectMake(0, 0, 320, 300);
    [imageM setImage:[UIImage imageNamed:@"A.png"]];
    [self.view addSubview:imageM];
    [imageM release];
    
    kind = ZoomIn;
    
    UIButton* btnAnimation = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnAnimation.frame = CGRectMake(10, 340, 300, 40);
    [btnAnimation setTitle:@"Animation" forState:UIControlStateNormal];
    [btnAnimation addTarget:self action:@selector(GoAnimation:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnAnimation];
    [btnAnimation release];
}


-(void)GoAnimation:(id)sender
{
    switch (kind)
    {
        /**  放大视图    **/
        case ZoomIn:
        {
            //开始动画块
            [UIView beginAnimations:@"ZoomIn" context:NULL];
            //动画块时长
            [UIView setAnimationDuration:1.0f];
            //CGRectInset返回中心点不变,比原视图大或小的视图
            imageM.frame = CGRectInset(imageM.frame,-CGRectGetWidth(imageM.frame),-CGRectGetHeight(imageM.frame));
            //提交动画块并开始执行动画块
            [UIView commitAnimations];
            
            kind = ZoomOut;
            break;
        }
            /**  缩小视图    **/
        case ZoomOut:
        {
            [UIView beginAnimations:@"ZoomOut" context:NULL];
            [UIView setAnimationDuration:1.0f];
            imageM.frame = CGRectInset(imageM.frame,CGRectGetWidth(imageM.frame)/3,CGRectGetHeight(imageM.frame)/3);
            [UIView commitAnimations];
            kind = FlipLeft;
            break;
        }
        case FlipLeft:
        {
            //开始动画
            [UIView beginAnimations:@"FlipLeft" context:NULL];
            //动画的曲线
[UIView setAnimationCurve:2];
            //动画时间
[UIView setAnimationDuration:2];
            //从哪个方向翻页
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:imageM cache:YES];
            //提交开始动画
[UIView commitAnimations];
            kind = FlipRight;
            break;
        }
        case FlipRight:
        {
            [UIView beginAnimations:@"FlipRight" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:imageM cache:YES];
[UIView commitAnimations];
            kind = CurlDown;
            break;
        }
        case CurlDown:
        {
            [UIView beginAnimations:@"CurlDown" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:imageM cache:YES];
[UIView commitAnimations];
            kind = CurlUp;
            break;
        }
        case CurlUp:
        {
            [UIView beginAnimations:@"CurlUp" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:imageM cache:YES];
[UIView commitAnimations];
            kind = ZoomIn;
            break;
        }
        default:
            break;
    }
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end


第十天:
(1)Json
#import "JsonViewController.h"
#import "JSON.h"
#import "JSONKit.h"


@interface JsonViewController ()


@end


@implementation JsonViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self Json1];
}
-(void)Json1
{
    NSString * resourcePath = [[NSBundle mainBundle] pathForResource:@"Jsondata1" ofType:@"txt"];
NSString * strJson = [NSString stringWithContentsOfFile:resourcePath encoding:NSUTF8StringEncoding error:NULL];


    //使用"JSON.h"解析,直接解析
NSDictionary * jsonDic = [strJson JSONValue];
    
    //使用jsonkit.h解析
    //NSDictionary *rootdic=[strJson objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode error:nil];


NSArray * versionArray = [jsonDic objectForKey:@"VERSION"];
NSDictionary * v1Dic = [versionArray objectAtIndex:0];

NSString * v1DicStr = [v1Dic objectForKey:@"简体中文"];
NSLog(@"v1DicStr = %@",v1DicStr);
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end


(2)GDataXM
#import "GDataXMLViewController.h"


@interface GDataXMLViewController ()


@end


@implementation GDataXMLViewController
/*
 header 里面/usr/include/libxml2
 */
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self parseXml1];
}
-(void)parseXml1
{
    NSString* filepath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"xml"];
    NSString* str = [[NSString alloc] initWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];


    NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
    //使用NSData对象初始化
    GDataXMLDocument* document=[[GDataXMLDocument alloc]initWithData:data options:0 error:nil];
    
    GDataXMLElement* element=[document rootElement];
    
    NSArray* bookArray=[element elementsForName:@"book"];
    for (id object in bookArray)
    {
        NSArray* titleArray=[object elementsForName:@"title"];
        
        GDataXMLElement* title=[titleArray objectAtIndex:0];
        NSLog(@"title=%@",[title stringValue]);
    }
    
    
    /*
    NSArray* bookArray=[element elementsForName:@"channel"];
    for (id object in bookArray)
    {
        NSArray* titleArray=[object elementsForName:@"item"];
        for(id objects in titleArray)
        {
            NSArray* ll = [objects elementsForName:@"title"];
            GDataXMLElement* title=[ll objectAtIndex:0];
            NSLog(@"title=%@",[title stringValue]);
            NSArray* lll = [objects elementsForName:@"description"];
            GDataXMLElement* des = [lll objectAtIndex:0];
            NSLog(@"des = %@",des);
        }
    }*/
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
(3)CreateXML
#import "CreateXMLViewController.h"
#import "News.h"
#import "XML1ViewController.h"


@interface CreateXMLViewController ()
{
    NSMutableString * stringData;
NSMutableArray * mutableArray;
    News* news;
}
@end


@implementation CreateXMLViewController


- (void)viewDidLoad
{
    
    [self CreateXML];
    [super viewDidLoad];
    UIButton* btnGo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnGo.frame = CGRectMake(0, 0, 320, 50);
    [btnGo addTarget:self action:@selector(AAA) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnGo];
    [btnGo release];
}


-(void)AAA
{
    XML1ViewController* xmlVC = [[XML1ViewController alloc]init];
    [self.navigationController pushViewController:xmlVC animated:YES];
}


-(void)CreateXML
{
    News * new1 = [[News alloc] initWithTitle:@"体育" andLink:[NSURL URLWithString:@"http://sina.tiyu.com"] andDate:[NSDate date]];
News * new2 = [[News alloc] initWithTitle:@"娱乐" andLink:[NSURL URLWithString:@"http://sina.yule.com"] andDate:[NSDate date]];
News * new3 = [[News alloc] initWithTitle:@"政治" andLink:[NSURL URLWithString:@"http://sina.zhengzhi.com"] andDate:[NSDate date]];
    News * new4 = [[News alloc] initWithTitle:@"天气" andLink:[NSURL URLWithString:@"http://sina.tianqi.com"] andDate:[NSDate date]];
    News * aNew = [[News alloc]initWithTitle:@"NBA"andLink:[NSURL URLWithString:@"http://www.baidu.com"]andDate:[NSDate date]];
    mutableArray = [[NSMutableArray alloc]init];
    [mutableArray addObject:new1];
    [mutableArray addObject:new2];
    [mutableArray addObject:new3];
    [mutableArray addObject:new4];
[mutableArray addObject:aNew];
    [new1 release];
    [new2 release];
    [new3 release];
    [new4 release];
[aNew release];
    
stringData = [NSMutableString stringWithString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"];
[stringData appendString:@"<rss version=\"2.0\">\n"];
[stringData appendString:@"\t<channel>\n"];
for(int i = 0; i < [mutableArray count]; i++)
{
News * new = [mutableArray objectAtIndex:i] ;
news = new;
NSDateFormatter * formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat: @"yyyy-MM-dd HH:mm"];
[stringData appendString:@"\t\t<item>\n"];
[stringData appendString:@"\t\t\t<title>"];
[stringData appendString:news.title];
[stringData appendString:@"</title>\n\t\t\t<link>"];
[stringData appendString:[NSString stringWithFormat:@"%@",news.link]];
[stringData appendString:@"</link>\n\t\t\t<pubDate>"];
[stringData appendString:[formatter stringFromDate:news.date]];
[stringData appendString:@"</pubDate>\n\t\t</item>\n"];
}
[stringData appendString:@"\t</channel>\n"];
[stringData appendString:@"</rss>"];

NSLog(@"*****stringdata*****\n%@",stringData);
NSArray * researchPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * filePath = [[researchPath objectAtIndex:0] stringByAppendingPathComponent:@"news.xml"];
NSLog(@"filePath:%@",filePath);
[stringData writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
if ([stringData writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL])
    {
UIAlertView * alt = [[UIAlertView alloc]initWithTitle:@"Create XMLFile"
                        message:@"Succeed Create"
                       delegate:nil
              cancelButtonTitle:@"OK"
              otherButtonTitles:nil];
[alt show];
[alt autorelease];
}
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
(4)XML
#import "XML1ViewController.h"
#import "ShowXMLViewController.h"


@interface XML1ViewController ()<UITableViewDataSource,UITableViewDelegate,NSXMLParserDelegate>
{
    NSMutableArray* data; // title, pubDate, link
//存储当前解析的元素(标签)的值
    NSMutableDictionary* curElement;
//当前子元素(标签)的值
    NSMutableString* curText;
    
    UITableView* tableXML;
}
@end


@implementation XML1ViewController


- (void)viewDidLoad
{
    data = [[NSMutableArray alloc] init];
    curElement = [[NSMutableDictionary alloc] init];
    curText = [[NSMutableString alloc] init];
    
    
    NSString* strPath=[[NSBundle mainBundle] pathForResource:@"news" ofType:@"xml"];
    
    NSString* xmlStr=[[NSString alloc]initWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
    
    
    NSData* datas=[xmlStr dataUsingEncoding:NSUTF8StringEncoding];


    if(datas == nil )
    {
        NSLog(@"File not ready.");
        return;
    }

//解析XML文件步骤:
//1.创建XML解析器NSXMLParser的实例(使用包含xml数据的缓冲区对象);
//2.设置XML解析器的委托对象NSXMLParserDelegate;
//3.开始事件驱动的异步解析过程;
//4.实现委托的回调方法

// parse XML
    NSXMLParser* parser =[[NSXMLParser alloc]initWithData:datas];//1.创建NSXMLParser实例
    parser.delegate = self;//2.设置XML解析器的委托
    [parser parse];        //3.开始XML解析
    [parser release];
    
    [super viewDidLoad];
    tableXML = [[UITableView alloc]init];
    tableXML.frame = CGRectMake(0, 0, 320, 460);
    [tableXML setDataSource:self];
    [tableXML setDelegate:self];
    [self.view addSubview:tableXML];
}


//当我们进入这个回调时,我们可以初始化数据:
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
[data removeAllObjects];
    NSLog(@"a");
}


//开始分析一个元素(发现该元素的起始标签)
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
{
    NSLog(@"b");
if ([elementName isEqualToString:@"item"]) {
        [curElement removeAllObjects];//清空字典中所有的对象
    }
    else if ([elementName isEqualToString:@"title"]){
        [curText setString:@""];
    }
    else if ([elementName isEqualToString:@"link"]){
        [curText setString:@""];
    }
    else if ([elementName isEqualToString:@"pubDate"]){
        [curText setString:@""];
    }
}


//发现该元素的值时调用
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    NSLog(@"c");
[curText appendString:string];
}


//结束分析一个元素(发现该元素的结束标签)
- (void)parser:(NSXMLParser *)parser
 didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
{
    NSLog(@"d");
if ([elementName isEqualToString:@"item"])
    {
        [data addObject:[NSDictionary dictionaryWithDictionary:curElement]];
    }
    else if ([elementName isEqualToString:@"title"]){
        [curElement setObject:[NSString stringWithString: curText] forKey:@"title"];
    }
    else if ([elementName isEqualToString:@"link"]){
        [curElement setObject:[NSString stringWithString: curText] forKey:@"link"];
    }
    else if ([elementName isEqualToString:@"pubDate"]){
        [curElement setObject:[NSString stringWithString: curText] forKey:@"pubDate"];
    }
}


//当所有的分析都完成之后,我们会得到parserDidEndDocument:方法的回调。到这个时候,我们所有要做的就是去显示更新我们从XML所得到的数据
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
[tableXML reloadData];
}




#pragma mark -
#pragma mark Table view data source


// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [data count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
// Configure the cell.
NSDictionary* dic = [data objectAtIndex:indexPath.row];
cell.textLabel.text = [dic objectForKey:@"title"];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShowXMLViewController* showVC = [[ShowXMLViewController alloc]init];
    showVC.dic = [data objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:showVC animated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end


第九天:
(1)
#import "Show1ViewController.h"
/*
 UIWebView的loadRequest可以用来加载一个url,
 它需要一个NSURLRequest参数.
*/
@interface Show1ViewController ()<UITextFieldDelegate,UIWebViewDelegate>
{
    UITextField* urlField;
    UIWebView* webView;
    UIActivityIndicatorView* activity;
}
@end


@implementation Show1ViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    urlField = [[UITextField alloc]init];
    [urlField setFrame:CGRectMake(0, 0, 250, 30)];
    [urlField setTextAlignment:1];
    [urlField setBorderStyle:1];
    [self.view addSubview:urlField];
    [urlField setDelegate:self];
    [urlField release];
    
    webView = [[UIWebView alloc]init];
    [webView setFrame:CGRectMake(0, 30, 320, 400)];
    [webView setDelegate:self];
    [self.view addSubview:webView];
    [webView release];
    
    activity = [[UIActivityIndicatorView alloc]init];
    activity.frame = CGRectMake((320-30)/2, (480-30)/2, 30, 30);
    [activity setActivityIndicatorViewStyle:1];
    [activity setHidesWhenStopped:YES];
    [activity setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:activity];
    [activity release];
    
    UIButton* btnGo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btnGo setFrame:CGRectMake(260, 0, 50, 30)];
    [btnGo setTitle:@"Go" forState:UIControlStateNormal];
    [btnGo addTarget:self action:@selector(GoUrl) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnGo];
}


-(void)GoUrl
{
    [urlField resignFirstResponder];
    NSURL* url = [NSURL URLWithString:urlField.text];
    NSURLRequest* request = [[NSURLRequest alloc]initWithURL:url];
    [webView loadRequest:request];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


//页面重定向时调用,每次加载的时候都会调用这个方法,可以用这个方法进行一些过滤
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"页面重定向");
    return YES;
}


//开始加载web页面的时候调用
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"Start load WebView");
    [activity startAnimating];
}


//结束加载web页面的时候调用
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"End load WebView");
    [activity stopAnimating];
}


//加载失败的时候调用这个方法
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [activity stopAnimating];
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"信息提示" message:@"加载失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alertView show];
}


@end


(2)上传下载
#import "ASIViewController.h"


@interface ASIViewController ()<NSURLConnectionDataDelegate>
{
    NSMutableData* _mutableData;
    UITextView* textView;
}
@end


@implementation ASIViewController


///
//NSURLConnection同步请求
-(void)LoadData4
{
    // 要请求的地址
    NSString *urlString=URL;
    // 将地址编码
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    // 实例化NSMutableURLRequest,并进行参数配置
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData]; //设置缓存
    [request setTimeoutInterval: 60]; //请求时间
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    
    // Response对象,用来得到返回后的数据,比如,用statusCode==200 来判断返回正常
    NSHTTPURLResponse *response;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                               returningResponse:&response error:nil];
    
    // 处理返回的数据
    NSString *strReturn = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",strReturn);
    NSLog(@"%d",[response statusCode]);
    // 对象还是要释放的
    [request release];
    [strReturn release];
}


//
/*
 使用NSURLConnection创建异步下载请求。此时需要NSURLConnectionDelegate协议方法
*/
//下载数据
-(void)downLoadData
{
    NSString* userName = @"neworigin";//用户名
    //下载数据URL
    //NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",GET_URL,userName]];
    NSURL* url = [NSURL URLWithString:URL];
    //创建请求的对象
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    //创建URLConnetion对象,并设置当前类的对象为代理
    NSURLConnection* connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if(connection)
    {
        NSLog(@"创建成功");
    }
    else
    {
        NSLog(@"创建失败");
    }
}
//请求失败代用
-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError *)error
{
    NSLog(@"请求数据失败");
}
//请求得到响应时调用,在此方法中将_mutableData清空
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [_mutableData setData:[NSData data]];
}
//接收到数据时调用,并将接收到得data追加到_mutableData中
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data
{
    [_mutableData appendData:data];
}
//请求完成后,将_mutableData转成字符串并输出
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString* str = [[NSString alloc]initWithData:_mutableData encoding:NSUTF8StringEncoding];
    textView.text = str;
}



//上传数据
-(void)updateData
{
    NSString* userName = @"neworigin";
    //需要上传的内容
    NSString* content = @"我要把这几个文字提交到服务器";
    NSData* postData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",POST_URL,userName]];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPBody:postData];//设置请求体,即上传的内容
    [request setHTTPMethod:@"POST"];//设置请求方式为POST
    [request setValue:[NSString stringWithFormat:@"%d",postData.length] forHTTPHeaderField:@"Content-length"];//设置http头
    NSURLConnection* connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if(connection)
    {
        NSLog(@"创建成功");
    }
    else
    {
        NSLog(@"创建失败");
    }
}


///
//使用NSURLConnection的sendAsynchronousRequest方法创建异步下载请求
-(void)LoadData2
{
    NSString* userName = @"neworigin";//用户名
    //下载数据URL
    //NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",GET_URL,userName]];
    NSURL* url = [NSURL URLWithString:URL];
    //创建请求的对象
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    NSOperationQueue* queue = [NSOperationQueue mainQueue];//异步上传只能在主主线程队列中
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse* response,NSData* data,NSError* connectionError)
     {
         if(!connectionError)
         {
             NSString* str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
             textView.text = str;
         }
     }];
}
//使用NSURLConnection的sendAsynchronousRequest方法创建同步下载请求
-(void)LoadDate3
{
    NSString* userName = @"neworigin";//用户名
    //下载数据URL
    //NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",GET_URL,userName]];
    NSURL* url = [NSURL URLWithString:URL];
    //创建请求的对象
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString* str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    textView.text = str;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    textView = [[UITextView alloc]init];
    [textView setFrame:CGRectMake(0, 0, 320, 460)];
    [textView setEditable:NO];
    [textView setFont:[UIFont systemFontOfSize:20.0f]];
    [self.view addSubview:textView];
    [textView release];
    
    _mutableData = [[NSMutableData alloc] init];
    //[self downLoadData];
    //[self LoadData2];
    //[self LoadDate3];
    
    //[self updateData];
    [self LoadData4];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end


第八天:数据库


(1)FMDB
#import "FMDBViewController.h"
#import "FMDatabase.h"


@interface FMDBViewController ()
{
    FMDatabase *db;
}
@end


@implementation FMDBViewController
/*
 iOS中原生的SQLite API在使用上相当不友好,在使用时,非常不便。于是,就出现了一系列将SQLite API进行封装的库,例如FMDB、PlausibleDatabase、sqlitepersistentobjects等,FMDB (https://github.com/ccgus/fmdb) 是一款简洁、易用的封装库,这一篇文章简单介绍下FMDB的使用。
 
 FMDB常用类:
 
 FMDatabase : 一个单一的SQLite数据库,用于执行SQL语句。
 
 FMResultSet :执行查询一个FMDatabase结果集。
 
 FMDatabaseAdditions:一个SQLite新增加的产物
 
 */






/*
 要注意的是,在iOS环境下,只有document directory 是可以进行读写的。在写程式时用的那个Resource资料夹底下的东西都是read-only。因此,建立的资料库要放在document 资料夹下。方法如下:
 */
//打开数据库
-(void)OpenDB
{
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"MyDataBase.db"];
    NSLog(@"%@",writableDBPath);
    db = [FMDatabase databaseWithPath:writableDBPath]; //连接FMDB
    if (![db open])
    {
        NSLog(@"Could not open db.");
        return ;
    }
    else
    {
        NSLog(@"Can open db.");
    }
}


/*
 这是FMDB裡很常用的指令,[FMDatabase_object executeUpdate:]后面用NSString塞入SQLite语法,就是创建一个表。
 */
//创建表
-(void)CreateTable
{
    //创建表
    [db executeUpdate:@"CREATE TABLE Person (name, age)"];
}


/*
 插入资料跟前面一样,用executeUpdate后面加语法就可以了。比较不同的是,因為插入的资料会跟Objective-C的变数有关,所以在string裡使用?号来代表这些变数。
 */
//插入数据
-(void)InsertwithValue1:(NSString*)value1 withValue2:(NSInteger)value2;
{
    [db executeUpdate:@"INSERT INTO Person (name,age) VALUES (?,?)",value1,[NSNumber numberWithInt:value2]];
    if ([db hadError])
    {
        NSLog(@"Err: %@", [db lastErrorMessage]);
    }
    else
    {
        NSLog(@"插入数据成功");
    }
}


/*
 取得特定的资料,则需使用FMResultSet物件接收传回的内容:
 用[rs next]可以轮询query回来的资料,每一次的next可以得到一个row裡对应的数值,并用[rs stringForColumn:]或[rs intForColumn:]等方法把值转成Object-C的型态。取用完资料后则用[rs close]把结果关闭。
 */
//查询数据
-(void)SelectTableName:(NSString*)tableName
{
    NSString* sql = [NSString stringWithFormat:@"SELECT * FROM %@",tableName];
    FMResultSet *rs = [db executeQuery:sql];
    while ([rs next])
    {
        NSString *name = [rs stringForColumn:@"name"];
        int age = [rs intForColumn:@"age"];
        NSLog(@"name = %@,age = %d",name,age);
    }
    [rs close];
}


//修改数据
-(void)UpdateName:(NSString*)name withAge:(NSInteger)age
{
    [db executeUpdate:@"UPDATE Person SET age = ? WHERE name = ?",[NSNumber numberWithInt:age],name];
}


//删除数据
-(void)DeleteTableWithName:(NSString*)name
{
    [db executeUpdate:@"DELETE FROM Person Where name = ?",name];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self OpenDB];
    //[self CreateTable];
    [self InsertwithValue1:@"caoyang" withValue2:23];
    [self SelectTableName:@"Person"];
    //[self UpdateName:@"caoyang" withAge:22];
    //[self DeleteTableWithName:@"caoyang"];
    //[self SelectTableName:@"Person"];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
(2)Sqlite
/*
 sqlite3* db; 数据库句柄,根文件句柄file类似
 sqlite3_stmt* stmt 这个相当于ODBC的command对象,用于保存编译好的SQL语句
 sqlite3_open() 打开数据库,没有数据库时创建
 sqqlite3_exec() 执行非产讯的sql语句
 sqlite3_step() 在调用sqlite3_prepare后,使用这个函数在记录集中移动
 sqlite3_close() 关闭数据库
*/


#import "SqliteViewController.h"


@interface SqliteViewController ()


@end


@implementation SqliteViewController


//获取Documents文件夹中文件路径
-(NSString*)getDouumentsPath
{
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsdir = [paths objectAtIndex:0];
    return [documentsdir stringByAppendingPathComponent:@"database.sql"];
}


//创建并打开数据库
-(void)openDB
{
    if(sqlite3_open([[self getDouumentsPath]UTF8String], &db)!=SQLITE_OK)
    {
        sqlite3_close(db);
        NSAssert(0,@"数据库打开失败");//停止应用程序并关闭数据库
    }
}


//创建表
-(void)createTableNamed:(NSString*)tableName withFiled1:(NSString*)field1 withField2:(NSString*)field2
{
    char* err;
    NSString* sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT,'%@' TEXT);",tableName,field1,field2];//创建表的sql语句
    
    if(sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err)!=SQLITE_OK)
    {
        sqlite3_close(db);
        NSAssert(0, @"创建表失败");
    }
}
//插入表中部分数据
-(void)insertTableNamed:(NSString*)tableName withField1:(NSString*)field1 withValue1:(NSString*)value1 withField2:(NSString*)field2 withValue2:(NSString*)value2
{
    NSString* sql = [NSString stringWithFormat:@"INSERT OR REPLACE INTO '%@'('%@','%@') VALUES ('%@','%@')",tableName,field1,field2,value1,value2];
    char* err;
    if(sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err)!=SQLITE_OK)
    {
        sqlite3_close(db);
        NSAssert(0, @"插入数据库失败");
    }
}
//查询数据库
-(void)selectAllFromTableName:(NSString*)tableName
{
    NSString* sql = [NSString stringWithFormat:@"SELECT * FROM '%@'",tableName];
    sqlite3_stmt* statement; //用于保存编译好的sql语句
    if(sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil)==SQLITE_OK)
    {
        while (sqlite3_step(statement)==SQLITE_ROW)
        {
            char* field1 = (char*)sqlite3_column_text(statement, 1);
            NSString* strField1 = [[NSString alloc]initWithUTF8String:field1];
            
            char* field2 = (char*)sqlite3_column_text(statement, 2);
            NSString* strField2 = [[NSString alloc]initWithUTF8String:field2];
            NSLog(@"userName = %@, passWord = %@",strField1,strField2);
        }
        sqlite3_finalize(statement);
    }
}


//修改表中数据
-(void)updateTableNamed:(NSString*)tableName withField1:(NSString*)field1 withValue1:(NSString*)value1 withField2:(NSString*)field2 withValue2:(NSString*)value2
{
    [self openDB];
    NSString* sql = [NSString stringWithFormat:@"UPDATE %@ SET %@='%@' WHERE %@ = '%@'",tableName,field2,value2,field1,value1];
    char* err;
    if(sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err)!=SQLITE_OK)
    {
        sqlite3_close(db);
        NSAssert(0, @"修改数据库失败");
    }
}


//删除表中某条数据
-(void)deleteTableName:(NSString*)tableName withField1:(NSString*)field1 withValue1:(NSString*)value1
{
    [self openDB];
    NSString* sql = [NSString stringWithFormat:@"Delete FROM %@ WHERE %@ = '%@'",tableName,field1,value1];
    char* err;
    if(sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err)!=SQLITE_OK)
    {
        sqlite3_close(db);
        NSAssert(0, @"删除数据库失败");
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self openDB];
    [self createTableNamed:@"Login" withFiled1:@"username" withField2:@"password"];
    //[self insertTableNamed:@"Login" withField1:@"username" withValue1:@"aaa" withField2:@"password" withValue2:@"bbb"];
    [self selectAllFromTableName:@"Login"];
    //[self updateTableNamed:@"Login" withField1:@"username" withValue1:@"aaa" withField2:@"password" withValue2:@"mmm"];
    NSLog(@"===============================");
    //[self deleteTableName:@"Login" withField1:@"username" withValue1:@"aaa"];
    //[self selectAllFromTableName:@"Login"];
    sqlite3_close(db);
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end


第七天: OtherViewController
#import "OtherViewController.h"




#define SizeOfImage 6


@interface OtherViewController ()<UIScrollViewDelegate>
{
    UIScrollView* scrollView;
    UIPageControl* pageControl;
    UIScrollView* smallScrollView;
}
@end


@implementation OtherViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    scrollView = [[UIScrollView alloc]init];
    scrollView.frame = CGRectMake(0, 0, 320, 200);
    //设置控件的滑动空间
    scrollView.contentSize = CGSizeMake(320*SizeOfImage, 200);
    //设置滚动条
    scrollView.showsHorizontalScrollIndicator = YES;
    scrollView.showsVerticalScrollIndicator = YES;
    //分页显示
    scrollView.pagingEnabled = YES;
    [scrollView setDelegate:self];
    [self.view addSubview:scrollView];
    [scrollView release];
    
    //在scrollView上添加图片
    for(int i=0;i<SizeOfImage;i++)
    {
        UIImageView* imageView = [[UIImageView alloc]initWithFrame:CGRectMake(320*i, 0, 320, 200)];
        [imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"big%d.png",i]]];
        [scrollView addSubview:imageView];
        [imageView release];
    }
    
    //pageControl
    pageControl = [[UIPageControl alloc]init];
    pageControl.frame = CGRectMake(100, 210, 120, 10);
    //设置点的个数
    pageControl.numberOfPages=SizeOfImage;
    //设置当前点位置
    pageControl.currentPage=0;
    [pageControl setBackgroundColor:[UIColor blueColor]];
    //添加事件方法
    [pageControl addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:pageControl];
    [pageControl release];
    
    smallScrollView = [[UIScrollView alloc]init];
    smallScrollView.frame = CGRectMake(80, 230, 160, 100);
    //设置控件的滑动空间
    smallScrollView.contentSize = CGSizeMake(160*SizeOfImage, 100);
    //设置滚动条
    smallScrollView.showsHorizontalScrollIndicator = YES;
    smallScrollView.showsVerticalScrollIndicator = YES;
    smallScrollView.delegate = self;
    smallScrollView.pagingEnabled = YES;
    [self.view addSubview:smallScrollView];
    [smallScrollView release];
    
    //在scrollView上添加图片
    for(int i=0;i<SizeOfImage;i++)
    {
        /*
        UIImageView* imageView = [[UIImageView alloc]initWithFrame:CGRectMake(160*i, 0, 160, 100)];
        [imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"small%d.png",i]]];
        [smallScrollView addSubview:imageView];
        [imageView release];
         */
        UIImage* image = [UIImage imageNamed:[NSString stringWithFormat:@"small%d.png",i]];
        DefaultView* defView = [[DefaultView alloc]initWithFrame:CGRectMake(i*160, 0, 160, 100) image:image tag:i];
        
        [smallScrollView addSubview:defView];
    }


}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView1
{
    CGPoint offset=scrollView1.contentOffset;
    CGRect bounds=scrollView1.frame;
    [pageControl setCurrentPage:offset.x/bounds.size.width];
}
-(void)pageTurn:(id)sender
{
    CGRect rect=CGRectMake(pageControl.currentPage*320,0,320,200);
    [scrollView scrollRectToVisible:rect animated:YES];
}


//滑动小的scrollView的时候,上面的大图片也跟着动
- (void)scrollViewDidScroll:(UIScrollView *)scrollViews
{
    if (scrollViews == smallScrollView)
    {
        NSInteger index = smallScrollView.contentOffset.x/160;
        pageControl.currentPage = index+1;
        [scrollView scrollRectToVisible:CGRectMake(320*index, 0, 320, 200) animated:YES];
    }
}


-(void)setValue:(NSInteger)value
{
    NSLog(@"%d",value);
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end


第六天:
(1)tableview
//DataSource非必须实现
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
//DataSource必须实现
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arrayM count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*
    static NSString* CellIdentifier = @"cell";
    //cell的重用
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell==nil)
    {
        //初始化一个cell
        //这里的Style是一个枚举
        cell = [[UITableViewCell alloc]initWithStyle:0 reuseIdentifier:CellIdentifier];
        
        //这里是在最后面加上一个->
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    //cell.textLabel.text = @"a";
    
    //cell.textLabel.text = [arrayM objectAtIndex:[indexPath row]];
    //Movie* mm = (Movie*)[arrayM objectAtIndex:indexPath.row];
    //cell.textLabel.text = mm.title;
    //return cell;
    */
    
    static NSString* CellIdentifier = @"Cell";
    //cell的重用
    ShowCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell==nil)
    {
        //初始化一个cell
        //这里的Style是一个枚举
        cell = [[ShowCell alloc]initWithStyle:0 reuseIdentifier:CellIdentifier];
        
        //这里是在最后面加上一个->
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    //cell.textLabel.text = @"a";
    
    //cell.textLabel.text = [arrayM objectAtIndex:[indexPath row]];
    Movie* mm = (Movie*)[arrayM objectAtIndex:indexPath.row];
    cell.title.text = mm.title;
    cell.money.text = mm.money;
    cell.description.text = mm.description;
    cell.imageV.image = [UIImage imageNamed:@"..."];
    return cell;
}




//Delegate
//是否可以编辑row
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


//点击编辑按钮,
-(void)LeftDo:(id)sender
{
    if(tableViewN.editing)
    {
        [tableViewN setEditing:NO animated:YES];
    }
    else
    {
        [tableViewN setEditing:YES animated:YES];
    }
}


//设置单元格编辑的样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row]%2==0)
    {
        return UITableViewCellEditingStyleDelete;
    }
    else
    {
        return UITableViewCellEditingStyleInsert;
    }
}


//删除或者添加单元格
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle==UITableViewCellEditingStyleDelete)
    {
        [arrayM removeObjectAtIndex:[indexPath row]];
        [tableView reloadData];
    }
    else if(editingStyle==UITableViewCellEditingStyleInsert)
    {
        Movie* movies = [[Movie alloc]initWithTitle:@"大上海" andMoney:@"123" andDescription:@"Am"];
        [arrayM addObject:movies];
        NSIndexPath* path = [NSIndexPath indexPathForRow:[arrayM count]-1 inSection:0];
        [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationFade];
    }
}


//设置按钮的名称
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row]%2==0)
    {
        return @"删除A";
    }
    else
    {
        return @"添加A";
    }
}


//移动单元格
-(void)tableView:(UITableView*)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSInteger fromRow = sourceIndexPath.row;
    NSInteger toRow = destinationIndexPath.row;
    [arrayM exchangeObjectAtIndex:fromRow withObjectAtIndex:toRow];
    [tableView reloadData];
}


//单元格的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Movie* mo = (Movie*)[arrayM objectAtIndex:[indexPath row]];
    NSLog(@"...%@",mo.title);
    NSLog(@"...%@",mo.money);
    NSLog(@"...%@",mo.description);
    EditViewController* editVC = [[EditViewController alloc]init];
    editVC.editMovie = mo;
    editVC.navigationItem.title = mo.title;
    [self.navigationController pushViewController:editVC animated:YES];
}


//修改后刷新数据1
-(void)viewWillAppear:(BOOL)animated
{
    NSLog(@"..........");
    UITableView* tableView = (UITableView*)[self.view viewWithTag:TABLEVIEW];
    [tableView reloadData];
}


//添加按钮
-(void)RightDo:(id)sender
{
    Movie* mo = [[Movie alloc]init];
    [arrayM addObject:mo];
    EditViewController* editVC = [[EditViewController alloc]init];
    editVC.editMovie = mo;
    editVC.navigationItem.title = mo.title;
    [self.navigationController pushViewController:editVC animated:YES];
}


//进行排序
-(void)sort
{
    NSSortDescriptor* description = nil;
    switch (segmentControl.selectedSegmentIndex) {
        case 0:
            description = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
            break;
        case 1:
            description = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:NO];
            break;
        default:
            break;
    }
    [arrayM sortUsingDescriptors:[NSArray arrayWithObject:description]];
    [tableViewN reloadData];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}


/*
//设置表格试图的头部和尾部
-(NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"head";
}
-(NSString*)tableView:(UITableView*)tableView titleForFooterInSection:(NSInteger)section
{
    return @"footer";
}
 */


/*
//设置表格试图的头试图和尾试图
-(UIView*)tableview:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 10)];
    label.text = @"this is the tableView Header View";
    label.backgroundColor = [UIColor redColor];
    return label;
}
-(UIView*)tableview:(UITableView*)tableView viewForFooterInSection:(NSInteger)section
{
    UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 10)];
    label.text = @"this is the tableView Footer View";
    label.backgroundColor = [UIColor redColor];
    return label;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}
-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
*/
 
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
(2)tableviewcell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        title = [[UILabel alloc]init];
        [title setFrame:CGRectMake(10, 0, 80, 40)];
        [self.contentView addSubview:title];
        
        money = [[UILabel alloc]init];
        [money setFrame:CGRectMake(90, 0, 40, 40)];
        [self.contentView addSubview:money];
        
        description = [[UILabel alloc]init];
        [description setFrame:CGRectMake(140, 0, 100, 40)];
        [self.contentView addSubview:description];
        
        title.backgroundColor = money.backgroundColor = description.backgroundColor = [UIColor whiteColor];
        
        imageV = [[UIImageView alloc]init];
        imageV.frame = CGRectMake(200, 0, 40, 40);
        [self.contentView addSubview:imageV];
        [imageV release];
    }
    return self;
}
(3)
#import "ShowGViewController.h"
#import "Movie.h"
#import "Cal.h"
#import "EditViewController.h"
#import "ShowCell.h"


@interface ShowGViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate>
{
    UITableView* tableViewM;
    NSMutableArray* arrayX; //喜剧电影的数组
    NSMutableArray* arrayK; //惊悚电影的数组
    NSMutableArray* arrayG; //香港电影的数组
}
@end


@implementation ShowGViewController


- (void)viewDidLoad
{
    tableViewM = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 420) style:1];
    [tableViewM setDataSource:self];
    [tableViewM setDelegate:self];
    [tableViewM setBackgroundView:nil];
    [tableViewM setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:tableViewM];
    [super viewDidLoad];
    
    arrayG = [[NSMutableArray alloc]init];
    arrayK = [[NSMutableArray alloc]init];
    arrayX = [[NSMutableArray alloc]init];
    //3.初始化Movie来显示一些
    Movie* movie1 = [[Movie alloc]initWithTitle:@"香港1" andMoney:@"12" andDescription:@"table1"];
    Movie* movie2 = [[Movie alloc]initWithTitle:@"香港2" andMoney:@"34" andDescription:@"table2"];
    Movie* movie3 = [[Movie alloc]initWithTitle:@"香港3" andMoney:@"56" andDescription:@"table3"];
    [arrayG addObject:movie1];
    [arrayG addObject:movie2];
    [arrayG addObject:movie3];
    
    Movie* movie4 = [[Movie alloc]initWithTitle:@"惊悚1" andMoney:@"12" andDescription:@"table1"];
    Movie* movie5 = [[Movie alloc]initWithTitle:@"惊悚2" andMoney:@"34" andDescription:@"table2"];
    [arrayK addObject:movie4];
    [arrayK addObject:movie5];
    
    Movie* movie6 = [[Movie alloc]initWithTitle:@"喜剧1" andMoney:@"12" andDescription:@"table1"];
    Movie* movie7 = [[Movie alloc]initWithTitle:@"喜剧2" andMoney:@"34" andDescription:@"table2"];
    [arrayX addObject:movie6];
    [arrayX addObject:movie7];
    
    [movie1 release];
    [movie2 release];
    [movie3 release];
    [movie4 release];
    [movie5 release];
    [movie6 release];
    [movie7 release];
    
    UIBarButtonItem* rightButton = [[UIBarButtonItem alloc]initWithTitle:@"添加" style:UIBarButtonItemStyleBordered target:self action:@selector(RightDo:)];
    self.navigationItem.rightBarButtonItem = rightButton;
    [rightButton release];
}


//添加按钮
-(void)RightDo:(id)sender
{
    UIActionSheet* actionSheet = [[UIActionSheet alloc]initWithTitle:@"标题" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"喜剧电影",@"香港电影",@"惊悚电影", nil];
    [actionSheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    Movie* mo = [[Movie alloc]init];
    EditViewController* editVC = [[EditViewController alloc]init];
    if(buttonIndex==0)
    {
        NSLog(@"喜剧电影");
        [arrayX addObject:mo];
    }
    else if(buttonIndex==1)
    {
        NSLog(@"香港电影");
        [arrayG addObject:mo];
    }
    else if(buttonIndex==2)
    {
        NSLog(@"惊悚电影");
        [arrayK addObject:mo];
    }
    editVC.editMovie = mo;
    editVC.navigationItem.title = mo.title;
    [self.navigationController pushViewController:editVC animated:YES];
}


//修改后刷新数据1
-(void)viewWillAppear:(BOOL)animated
{
    [tableViewM reloadData];
}


//DataSource非必须实现
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
//DataSource必须实现
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section==0)
    {
        return [arrayG count];
    }
    else if(section==1)
    {
        return [arrayK count];
    }
    else if(section==2)
    {
        return [arrayX count];
    }
    return 0;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* CellIdentifier = @"Cell";
    //cell的重用
    ShowCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell==nil)
    {
        //初始化一个cell
        //这里的Style是一个枚举
        cell = [[ShowCell alloc]initWithStyle:0 reuseIdentifier:CellIdentifier];
        
        //这里是在最后面加上一个->
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if([indexPath section]==0)
    {
        Movie* mm = (Movie*)[arrayG objectAtIndex:indexPath.row];
        cell.title.text = mm.title;
        cell.money.text = mm.money;
        cell.description.text = mm.description;
    }
    else if([indexPath section]==1)
    {
        Movie* mm = (Movie*)[arrayK objectAtIndex:indexPath.row];
        cell.title.text = mm.title;
        cell.money.text = mm.money;
        cell.description.text = mm.description;
    }
    else if([indexPath section]==2)
    {
        Movie* mm = (Movie*)[arrayX objectAtIndex:indexPath.row];
        cell.title.text = mm.title;
        cell.money.text = mm.money;
        cell.description.text = mm.description;
    }
    return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section==0)
    {
        return @"香港片";
    }
    else if(section==1)
    {
        return @"惊悚片";
    }
    else if(section==2)
    {
        return @"喜剧片";
    }
    return @"";
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值