第一阶段的总结0816

程序运行的生命周期

 

 

对象的消失和出现的过程

 

viewDidLoad调用的时机是self.view 的getter方法的调用后

 

根据UIApplicationMain函数,程序将进入AppDelegate.m,这个文件是xcode新建工程时自动生成的。下面看一下AppDelegate.m文件,这个关乎着应用程序的生命周期。

 

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  2. {  
  3.     self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];  
  4.     // Override point for customization after application launch.  
  5.     self.window.backgroundColor = [UIColor whiteColor];  
  6.     [self.window makeKeyAndVisible];  
  7.     NSLog(@"iOS_didFinishLaunchingWithOptions");  
  8.     return YES;  
  9. }  
  10.   
  11. - (void)applicationWillResignActive:(UIApplication *)application  
  12. {  
  13.     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.  
  14.     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.  
  15.     NSLog(@"iOS_applicationWillResignActive");  
  16.   
  17. }  
  18.   
  19. - (void)applicationDidEnterBackground:(UIApplication *)application  
  20. {  
  21.     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.   
  22.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.  
  23.     NSLog(@"iOS_applicationDidEnterBackground");  
  24.   
  25. }  
  26.   
  27. - (void)applicationWillEnterForeground:(UIApplication *)application  
  28. {  
  29.     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.  
  30.     NSLog(@"iOS_applicationWillEnterForeground");  
  31.   
  32. }  
  33.   
  34. - (void)applicationDidBecomeActive:(UIApplication *)application  
  35. {  
  36.     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.  
  37.     NSLog(@"iOS_applicationDidBecomeActive");  
  38.   
  39. }  
  40.   
  41. - (void)applicationWillTerminate:(UIApplication *)application  
  42. {  
  43.     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.  
  44.     NSLog(@"iOS_applicationWillTerminate");  
  45.   
  46. }  


     1、application didFinishLaunchingWithOptions:当应用程序启动时执行,应用程序启动入口,只在应用程序启动时执行一次。若用户直接启动,lauchOptions内无数据,若通过其他方式启动应用,lauchOptions包含对应方式的内容。

     2、applicationWillResignActive:在应用程序将要由活动状态切换到非活动状态时候,要执行的委托调用,如 按下 home 按钮,返回主屏幕,或全屏之间切换应用程序等。

     3、applicationDidEnterBackground:在应用程序已进入后台程序时,要执行的委托调用。

     4、applicationWillEnterForeground:在应用程序将要进入前台时(被激活),要执行的委托调用,刚好与applicationWillResignActive 方法相对应。

     5、applicationDidBecomeActive:在应用程序已被激活后,要执行的委托调用,刚好与applicationDidEnterBackground 方法相对应。

     6、applicationWillTerminate:在应用程序要完全推出的时候,要执行的委托调用,这个需要要设置UIApplicationExitsOnSuspend的键值。 

     

初次启动:

 

2013-05-24 20:20:31.550 LifeIOS[451:c07] iOS_didFinishLaunchingWithOptions

2013-05-24 20:20:31.551 LifeIOS[451:c07] iOS_applicationDidBecomeActive

按下home键:

 

2013-05-24 20:22:17.349 LifeIOS[451:c07] iOS_applicationWillResignActive

2013-05-24 20:22:17.350 LifeIOS[451:c07] iOS_applicationDidEnterBackground

点击程序图标进入:

 

2013-05-24 20:22:56.913 LifeIOS[451:c07] iOS_applicationWillEnterForeground

2013-05-24 20:22:56.914 LifeIOS[451:c07] iOS_applicationDidBecomeActive

 

程序中没有设置UIApplicationExitsOnSuspend的值,程序不会彻底退出。

 

3.对象的之间的传值

 

  对于这方面感觉,自己还比较清晰。主要是找到对象(在对象与对象之间碰面时是最好时机)

 

4.XML/HTML的解析

     XML

    NSString *str=@"<stu><stu1>stu1</stu1><stu2>age</stu2></stu>";
    NSDictionary *dic=[NSDictionary dictionaryWithXMLString:str];
    NSLog(@"%@",dic);
    

HTML解析

 

    NSString *html=[[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://dict.youdao.com/search?q=link&keyfrom=dict.index"] encoding:NSUTF8StringEncoding error:nil];
    
    NSLog(@"%@",html);
    HTMLParser *parser =[[HTMLParser alloc] initWithString:html error:nil];
    HTMLNode *bNode=[parser body];
    NSArray *node=[bNode findChildrenWithAttribute:@"class" matchingName:@"keyword" allowPartial:YES];
    NSLog(@"==%@",node.description);
    for (HTMLNode *no in node)
    {
        NSLog(@"++%@",[no contents]);
    }
    
    NSArray *node1=[bNode findChildrenWithAttribute:@"class" matchingName:@"pronounce" allowPartial:YES];
    for (HTMLNode *no1 in node1)
    {
        NSLog(@"+++%@",[no1 contents]);
    }

    NSError *error;
    NSString *html =
    @"<ul>"
    "<li><input type='image' name='input1' value='string1value' /></li>"
    "<li><input type='image' name='input2' value='string2value' /></li>"
    "</ul>"
    "<span class='spantext'><b>Hello World 1</b></span>"
    "<span class='spantext'><b>Hello World 2</b></span>";
    HTMLParser *parser = [[HTMLParser alloc] initWithString:html error:&error];
    
    if (error) {
        NSLog(@"Error: %@", error);
        return;
    }
    
    HTMLNode *bodyNode = [parser body];
    
    NSArray *inputNodes = [bodyNode findChildTags:@"input"];
    
    for (HTMLNode *inputNode in inputNodes) {
        if ([[inputNode getAttributeNamed:@"name"] isEqualToString:@"input2"]) {
            NSLog(@"-----%@", [inputNode getAttributeNamed:@"value"]); //Answer to first question
        }
    }
    
    NSArray *spanNodes = [bodyNode findChildTags:@"span"];
    
    for (HTMLNode *spanNode in spanNodes) {
        if ([[spanNode getAttributeNamed:@"class"] isEqualToString:@"spantext"]) {
            NSLog(@"===%@", [spanNode rawContents]); //Answer to second question
        }
    }

 

 

代理的应用

在IOS开发中协议和委托是两个密不可分的概念(也可以说是不同的设计模式,只不过在这里我们把他们讲在一起,因为我们常常都是这么用的):确 切来说,协议[protocol]定义了一种规范,使遵循它的类具备一种能力。委托[delegate]则是制定了一种"一个类中需要做的事情交给另一个 类来完成"的途径,通过委托别的类,来调用协议里的方法,委托也可以说是Object-C中实现多继承的一种方式。
委托delegate
在 apple提供的IOS SDK里可以看到很多的delegate,比如我们常用的UITableView,因为我们没有源码,就没有办法知道UITableView里的所谓的 cell是如何增加,删除,复用的。但开发者面对的开发要求使开发者必须具备能够操作这些cell的能力,针对这种情况,各种Delegate就显得非常 重要。
委托delegate是一个简单而强大的设计模式,在此模式中,可以允许一个对象代表另一个对象执行某个操作,或者相互协同操作。
一个很常见的场景就是网络下载数据操作,因为网络数据下载的延迟,一般都会采取多线程的机制,等到数据下载完成之后再通知主线程完成必要的操作。在这个场景中,我们完全可以在主线程实现一个代理方法,在该方法中操作下载好的数据。
协议protocol:
一个完整协议定义如下:
@protocol  协议名
声明方法
@end
其中"声明方法"可以用@required和@optional关键字修饰:
@required 表示我们用到这个协议的时候必须实现这个协议的方法
@optional 表示我们可选择性实现这些方法。
一个类需要遵循的协议在接口声明中的<>填写即可。
示例:
#import <UIKit/UIKit.h>  
@interface MyViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>//声明继承UIViewController类,遵循UITableViewDataSource和 UITableViewDelegate协议。
@property (strong, nonatomic) NSDictionary *names;  
@property (strong, nonatomic) NSArray *keys;  
@end
那么我们需要在MyViewController类中实现UITableViewDataSource和UITableViewDelegate协议里面的委托方法。
理解协议和委托的关系我们需要搞清楚如下几个问题:
1,一个对象的委托是哪个对象,需要干什么事情;
2,被委托的类需要在自身的interface中声明协议:<XXXDelega>,表示该来需要实现XXXDelega协议的方法。
3,在被委托的类里定义一个委托类的对象,并设置XXX.dalegate = self。把本类设置成委托对象。然后在本类中实现协议方法。
委托与协议分析示例:
假设公司老板日常的工作是管理公司、起草文件和接电话。
其中管理公司是老板要亲自做的。而起草文件与接电话老板希望秘书来帮忙,于是对秘书的要求就是要懂得文字编辑,要能帮助领导接电话。而这两项要求便是协议。
 
异步下载
 
#pragma mark - NSURLConnectionDataDelegate
//4. 只有出错才会到这里
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Failed: %@", error);
}

//1. 先接受到响应信息,能够知道等下接受的数据是什么样的
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Response: %@", response);
    NSLog(@"Total length: %lld", [response expectedContentLength]);
    
}

//NSFileHandle

//2. 分次接受数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (connection==connection1)
    {
        [_mData1 appendData:data];
    }
    else
    {
        [_mData2 appendData:data];
    }
}

- (void)getImage:(NSDictionary *)str imgView:(UIImageView *)imgView label:(UILabel*)lab
{
    NSString *string=[NSString stringWithFormat:@"http://112.124.25.143:8080/TradeCms%@",str[@"imgUrl"]];
    NSURL *url1=[NSURL URLWithString:string];
    NSURLRequest *imageRequest=[NSURLRequest requestWithURL:url1 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //            NSLog(@"--@--%@",url1);
    
    [NSURLConnection sendAsynchronousRequest:imageRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
//         NSLog(@"%@",data);
         UIImage *image=[UIImage imageWithData:data];
         imgView.image=image;
         lab.text=str[@"title"];
     }];
//    NSData *imageData=[NSURLConnection sendSynchronousRequest:imageRequest returningResponse:nil error:nil];
    //        NSData *imageData=[NSData dataWithContentsOfURL:url1 options:NSDataReadingMappedIfSafe error:nil];
//    UIImage *image=[UIImage imageWithData:imageData];
//    return  image;
}

- (void)getImage:(NSDictionary *)str flag:(int)fg
{
    NSString *string=[NSString stringWithFormat:@"http://112.124.25.143:8080/TradeCms%@",str[@"smallImg"]];
    NSURL *url1=[NSURL URLWithString:string];
    //    NSLog(@"--@--%@",url1);
    NSURLRequest *imageRequest=[NSURLRequest requestWithURL:url1 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //            NSLog(@"--@--%@",url1);
    [NSURLConnection sendAsynchronousRequest:imageRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         //         NSLog(@"%@",data);
         flag++;
         NSString *key=[NSString stringWithFormat:@"%d",fg];
         [imgDic setObject:data forKey:key];
//         table.delegate=self;
//         table.dataSource=self;
//         [table reloadData];

         if (flag>9)
         {
             table.delegate=self;
             table.dataSource=self;
             [table reloadData];
             if ([activity isAnimating])
             {
                 [activity removeFromSuperview];
             }

         }
     }];
}

//3. 下载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (connection==connection1)
    {
        NSLog(@"conn1 finished...");
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:_mData1 options:NSJSONReadingAllowFragments error:nil];
//        NSLog(@"%@",dic);
        _mArray1=[dic objectForKey:@"contents"];
//        NSLog(@"%@",_mArray1);
        
        [self getImage:_mArray1[0]imgView:scrImageView1 label:xinXiLab];
        [self getImage:_mArray1[1]imgView:scrImageView2 label:xinXiLab2];
        [self getImage:_mArray1[2]imgView:scrImageView3 label:xinXiLab3];
//        if ([activity isAnimating])
//        {
//            [activity removeFromSuperview];
//        }
        
    }
    else
    {
        NSLog(@"conn2 finished...");

        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:_mData2 options:NSJSONReadingAllowFragments error:nil];
//        NSLog(@"%@",dic);
        _mArray2=[dic objectForKey:@"contents"];
//        NSLog(@"%@",_mArray2);

        for (int i=0; i<10; i++)
        {
            [self getImage:_mArray2[i] flag:i];
        }
//        table.delegate=self;
//        table.dataSource=self;
//        [table reloadData];
    }
  
}

 

 

 

 

posted @ 2014-08-16 09:26  曦阳  阅读(143)  评论(0编辑  收藏  举报