关于IOS程序开发的概览 IOS安全

桃汁 2017-10-31 11988

现在很多IOS开发人员做开发都是一知半解,程序质量确实令人担忧,所以还是希望大家能够熟练掌握前面的内容,开发过程中多思考,彻底理解程序运行的原理、机制。好了言归正传,不管怎么样正式进入IOS开发还是令人兴奋的

 

第一个iOS程序

iOS程序运行过程

文件结构

Storyboard

纯代码实现iOS开发

补充知识点

第一个iOS程序

首先打开XcodeCreate a new Xcode projectSingle View Application--输入项目名称,同时选择使用Objective-C语言,设备选择iPhone--接下来系统默认生成一个IOS项目模板。程序的运行过程

//

//  main.m

//  FirstIOS

//

//  Created by Kenshin Cui on 14-2-23.

//  Copyright (c) 2014Kenshin Cui. All rights reserved.

//#import <UIKit/UIKit.h>#import "AppDelegate.h"int main(int argc, char * argv[]) {

    @autoreleasepool {        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));

    }

}

这个默认的iOS程序就是从main函数开始执行的,但是在main函数中我们其实只能看到一个方法,这个方法内部是一个消息循环(相当于一个死循环),因此运行到这个方法UIApplicationMain之后程序不会自动退出,而只有当用户手动关闭程序这个循环才结束。这个方法有四个参数:

 

第一个参数和第二个参数其实就是main函数的参数,分别代表:参数个数、参数内容;

第三个参数代表UIApplication类(或子类)字符串,这个参数默认为nil则代表默认为UIApplication类,用户可以自定义一个类继承于这个类;如果为nil则等价于NSStringFromClass([UIApplication class]),大家可以自己试验,效果完全一样;UIApplication是单例模式,一个应用程序只有一个UIApplication对象或子对象;

第四个参数是UIApplication的代理类字符串,默认生成的是AppDelegate类,这个类主要用于监听整个应用程序生命周期的各个事件(其实类似于之前我们文章中提到的事件监听代理),当UIApplication运行过程中引发了某个事件之后会调用代理中对应的方法;

小技巧:

 

其实在Xcode中如果要看一些系统方法的解释或者参数说明,可以直接鼠标放到这个方法上,在Xcode右侧面板中就会给出帮助提示

 

也就是说当执行UIApplicationMain方法后这个方法会根据第三个参数创建对应的UIApplication对象,这个对象会根据第四个参数AppDelegate创建并指定此对象为UIApplication的代理;同时UIApplication会开启一个消息循环不断监听应用程序的各个活动,当应用程序生命周期发生改变UIApplication就会调用代理对应的方法。

 

既然应用程序UIApplication是通过代理和外部交互的,那么我们就有必要清楚AppDelegate的操作细节,下面是UIApplication详细的代码:

 

AppDelegate.h

 

//

//  AppDelegate.h

//  

//

//  Created by Kenshin Cui on 14-2-23.

//  Copyright (c) 2014Kenshin Cui. All rights reserved.

//#import <UIKit/UIKit.h>@interface AppDelegate : UIResponder <UIApplicationDelegate>

 

@property (strong, nonatomic) UIWindow *window;

 

@end

AppDelegate.m

 

//

//  AppDelegate.m

//  

//

//  Created by Kenshin Cui on 14-2-23.

//  Copyright (c) 2014Kenshin Cui. All rights reserved.

//#import "AppDelegate.h"@implementation AppDelegate

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{    return YES;

}

 

- (void)applicationWillResignActive:(UIApplication *)application

{    // 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.

    // 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.}

 

- (void)applicationDidEnterBackground:(UIApplication *)application

{    // 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.

    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}

 

- (void)applicationWillEnterForeground:(UIApplication *)application

{    // 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.}

 

- (void)applicationDidBecomeActive:(UIApplication *)application

{    // 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.}

 

- (void)applicationWillTerminate:(UIApplication *)application

{    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.}

 

@end

这个类中定义了应用程序生命周期中各个事件的执行方法:

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;程序启动之后执行,只有在第一次程序启动后才执行,以后不再执行;

 

- (void)applicationWillResignActive:(UIApplication *)application;程序将要被激活时(获得焦点)执行,程序激活用户才能操作;

 

- (void)applicationDidEnterBackground:(UIApplication *)application;程序进入后台后执行,注意进入后台时会先失去焦点再进入后台;

 

- (void)applicationWillEnterForeground:(UIApplication *)application;程序将要进入前台时执行;

 

- (void)applicationDidBecomeActive:(UIApplication *)application;程序被激活(获得焦点)后执行,注意程序被激活时会先进入前台再被激活;

 

- (void)applicationWillTerminate:(UIApplication *)application;程序在终止时执行,包括正常终止或异常终止,例如说一个应用程序在后太运行(例如音乐播放软件、社交软件等)占用太多内存这时会意外终止调用此方法;

 

为了演示程序的生命周期,不妨在每个事件中都输出一段内容,简单调整上面的代码:

 

AppDelegate.m

 

//

//  AppDelegate.m

//  FirstIOS

//

//  Created by Kenshin Cui on 14-2-23.

//  Copyright (c) 2014Kenshin Cui. All rights reserved.

//#import "AppDelegate.h"@interface AppDelegate ()

 

@end

 

@implementation AppDelegate

            

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    NSLog(@"程序已经启动...");    return YES;

}

 

- (void)applicationWillResignActive:(UIApplication *)application {

    NSLog(@"程序将要失去焦点...");    // 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.

    // 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.}

 

- (void)applicationDidEnterBackground:(UIApplication *)application {

    NSLog(@"程序已经进入后台...");    // 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.

    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}

 

- (void)applicationWillEnterForeground:(UIApplication *)application {

    NSLog(@"程序将要进入前台...");    // 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.}

 

- (void)applicationDidBecomeActive:(UIApplication *)application {

    NSLog(@"程序已经获得焦点...");    // 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.}

 

- (void)applicationWillTerminate:(UIApplication *)application {

    NSLog(@"程序将要终止...");    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.}

 

-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application{

    

}

 

@end

 

相信通过上面运行过程大家会对整个运行周期有个大概了解。比较容易混淆的地方就是应用程序进入前台、激活、失去焦点、进入后台,这几个方法大家要清楚。如果一个应用程序失去焦点那么意味着用户当前无法进行交互操作,因此一般会先失去焦点再进入后台防止进入后台过程中用户误操作;如果一个应用程序进入前台也是类似的,会先进入前台再获得焦点,这样进入前台过程中未完全准备好的情况下用户无法操作。另外一般如果应用程序要保存用户数据会在注销激活中进行(而不是在进入后台方法中进行),因为如果用户双击Home不会进入后台只会注销激活;如果用户恢复应用状态一般在进入激活状态时处理(而不是在进入前台方法中进行),因为用户可能是从任务栏直接返回应用,此时不会执行进入前台操作。

 

当然,上面的事件并不是所有AppDelegate事件,而是最常用的一些事件,其他事件大家可以查阅官方文档,例如-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application;用于在内存占用过多发出内存警告时调用并通知对应的ViewController调用其内存回收方法。

 

文件结构

这里对于Xcode默认为我们生产的项目结果文件做一下简单介绍:

 

AppDelegate.h/.m):应用程序代理,主要用于监听整个应用程序生命周期中各个阶段的事件;

ViewController.h/.m):视图控制器,主要负责管理UIView的生命周期、负责UIView之间的切换、对UIView事件进行监听等;

Main.storyboard:界面布局文件,承载对应UIView的视图控件;

Images.xcassets:应用程序图像资源文件;

Info.plist:应用程序配置文件;

main.m:应用程序入口函数文件;

xxx-prefix.pch:项目公共头文件,此文件中的导入语句在编译时会应用到所有的类文件中,相当于公共引入文件(注意在Xcode6中没有提供此文件)

 

Storyboard

到目前为止我们还没有解释我们的程序是如何显示默认视图界面的。做过WinForm程序的朋友都知道每个Window窗口界面都有一个设计器(对应一个设计文件),其实在IOS中也可以通过设计工具设计界面不用编写代码,这个工具就是Interface Builder。用Interface Builder编辑的文件在iOS5之前是一个“.xib”文件,从IOS5开始进行了改进,使用“.storyboard”文件进行设计。其实在上面我们已经看到这个文件,这里重点说明一下Storyboard文件的使用。

 

在这个界面中整个核心就是右侧视图控制器ViewController,在ViewController中有一个视图UIView,这个视图用来放置其他用户操作控件。视图控制器左侧的箭头表示这个视图控制器是个主视图控制器,程序启动之后默认就会直接显示这个视图控制器的视图。我们可以在项目属性中通过修改“Main Interface”属性来修改主视图控制器。

 

要实现这个登录,那么接下来就是事件和属性绑定的问题,大家应该可以猜到登录的逻辑代码肯定在ViewController.m中编写,那么storyboard文件是如何关联到这个类的呢?如果我们在storyboard界面选中ViewControllerXcode右侧切换到Identity Inspector视图就会发现里面当前设置的是ViewController类,通过这个设置Main.storyboardViewController关联在一起。

 

那么如何在代码中读取两个TextField的值并通过点击按钮触发相关事件验证登录合法性呢?要想在代码中使用UITextField,并且添加按钮点击事件,则必须在ViewController.h中定义两个UITextField属性和一个登录方法。

 

ViewController

 

上面代码我们需要解释一下IBOutletIBAction,其余代码和我们之前写的ObjC没有任何区别。

 

IBOutlet:IBOutlet没有做任何操作,它的唯一作用就是告诉Interface Builder这个属性可以被关联到其中某个控件(在代码中可以看到代码前面多了空心圆点)。

IBAction:其实就是void,只是当你定义为IBActionInterface Builder中可以关联到某个控件的事件方法(后面的关联操作将会看到,而且我们在代码中也可以看到代码前面多了空心圆点);

下面看一下storyboard中的控件和代码中定义的属性和事件如何关联。Xcode为我们提供了几种方式来实现代码和storyboard控件的关联:

 

1.拖拽控件到代码中(首先点击Xcode右上方“Show the Assistant editor”切换对应视图,然后在代码中打开.h文件,同时打开Interface Builder,按住ctrl键拖拽控件到代码中相应的位置进行关联),关联后属性或方法前的空心圆变成实心表示已经关联到具体控件(注意:事实上,从控件拖拽到代码时如果代码中没有定义对应的属性和方法Interface Builder会自动生成代码)

 

controlToCode

 

2.从控件场景中拖拽控件到代码,关联后属性或方法前的空心圆变成实心表示已经关联到具体控件。(Interface Builder中点击左下角“Show Document outline”显示控件结构树,选中相应的控件按住Ctrl键拖拽到代码中的属性或方法上)

 

controlSceneToCode

 

3. 在控件上右键找到对应的属性或方法关联到代码中对应的属性或方法即可,关联后属性或方法前的空心圆变成实心表示已经关联到具体控件。

 

propertyToCode.gif

 

4.与方法3类似,不再截图,只是通过View Control Scene中的控件右键来关联,关联后属性或方法前的空心圆变成实心表示已经关联到具体控件。(在Interface Builder中点击左下角Show Document outline显示控件结构树,选中相应的控件右键拖拽到代码中的属性或方法上)

 

5.对于前面几种方法其实我们还可以直接从代码拖拽到控件上面,这里简单演示一种,其他情况大家可以自己试验。

 

codeToControl.gif

 

如果要删除关联,可以采用第三、第四种方式在控件上右键,在关联菜单中找到对应的关联删除即可。此外需要注意对于一个控件而言可能有多个事件,当我们使用第三种或第四种方式直接选择具体某个事件关联到login:方法自然没有问题,但是第一、第二、第五种方式没有提示我们关联到哪个事件而是使用一个控件的默认事件(对于UIButton就是Touch Up Inside事件)。

 

既然控件和代码属性或方法已经做了关联,这里我们看一下具体效果,这里简单修改一下ViewController.m

 

//

//  ViewController.m

//  FirstIOS

//

//  Created by Kenshin Cui on 14-2-23.

//  Copyright (c) 2014Kenshin Cui. All rights reserved.

//#import "ViewController.h"@interface ViewController ()

 

@end

 

@implementation ViewController

            

- (void)viewDidLoad {

    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}

 

-(void)login:(UIButton *)btn{    if ([_phoneNumber.text isEqual:@"123"]&&[_password.text isEqual:@"456"]) {

        NSLog(@"登录成功!");

    }

}

 

@end

这里实现了login:方法模拟登录的过程,可以发现当在手机号码中输入“123”,在密码中输入“456”点击登录会输出”登录成功!“。

 

纯代码实现iOS开发

storyboard进行界面设计固然不错,特别是对于初学者经常会使用设计器进行界面设计,但是实际开发过程中我们很多情况下会直接使用代码进行界面布局,特别是对于复杂的界面布局更是如此。下面我们就从一个空项目建立一个类似于前面的登录界面。

 

直接在Xcode中创建“Empty Application”(注意在Xcode6中这个选项已经没有了,这里采用Xcode5.1),此时会发现已经没有ViewControllerstoryboard文件,我们需要手动创建一个视图控制器(在项目中右键选择Objective-c class,默认继承自UIViewController,输入类名:KCMainViewController即可)。

 

新建的视图控制器默认情况下是无法加载到程序运行界面上的,此时需要在应用程序代理的程序加载完毕事件中手动加载并显示我们的视图。修改之前KCAppDelegate.m代码如下:

 

//  KCAppDelegate.m

//  IOSByCode

//

//  Created by Kenshin Cui on 14-2-23.

//  Copyright (c) 2014Kenshin Cui. All rights reserved.

//#import "KCAppDelegate.h"@implementation KCAppDelegate

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    // Override point for customization after application launch.    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];    return YES;

}

 

- (void)applicationWillResignActive:(UIApplication *)application

{    // 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.

    // 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.}

 

- (void)applicationDidEnterBackground:(UIApplication *)application

{    // 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.

    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}

 

- (void)applicationWillEnterForeground:(UIApplication *)application

{    // 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.}

 

- (void)applicationDidBecomeActive:(UIApplication *)application

{    // 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.}

 

- (void)applicationWillTerminate:(UIApplication *)application

{    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.}

 

@end

我们修改上面- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions的代码如下:

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{    //设置window属性(在KCAppDelegate中定义的window属性),初始化windows的大小和位置    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    // Override point for customization after application launch.

    //设置window的背景    self.window.backgroundColor = [UIColor whiteColor];    

    //初始化KCMainViewController    KCMainViewController *mainController=[[KCMainViewController alloc]init];    //设置自定义控制器的大小和window相同,位置为(00)    mainController.view.frame=self.window.bounds;    //设置此控制器为window的根控制器    self.window.rootViewController=mainController;    

    //设置window为应用程序主窗口并设为可见    [self.window makeKeyAndVisible];    return YES;

}

然后在我们自定义的KCMainViewController.m中添加一个UIImageView、两个控件UITextField和一个UIButton控件,并且实现具体的登录方法。

 

KCMainViewController.h

 

//

//  KCMainViewController.h

//  IOSByCode

//

//  Created by Kenshin Cui on 14-2-23.

//  Copyright (c) 2014Kenshin Cui. All rights reserved.

//#import <UIKit/UIKit.h>@interface KCMainViewController : UIViewController#pragma mark logo

@property (nonatomic,strong) UIImageView *logo;#pragma mark 手机号码

@property (nonatomic,strong) UITextField *phoneNumber;#pragma mark 密码

@property (nonatomic,strong) UITextField *password;#pragma mark 登录按钮

@property (nonatomic,strong) UIButton *loginButton;#pragma mark 点击事件

-(void)login:(UIButton *)btn;

 

@end

KCMainViewController.m

 

//

//  KCMainViewController.m

//  IOSByCode

//

//  Created by Kenshin Cui on 14-2-23.

//  Copyright (c) 2014Kenshin Cui. All rights reserved.

//#import "KCMainViewController.h"@interface KCMainViewController ()

 

@end

 

@implementation KCMainViewController

 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

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

}

 

- (void)viewDidLoad

{

    [super viewDidLoad];    // Do any additional setup after loading the view.

    //self.view.backgroundColor=[UIColor redColor];

    

    //添加图片    CGRect logoRect=CGRectMake(100, 50, 100, 200);

    _logo=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"LoginBackground.png"]];//设置图片    _logo.contentMode=UIViewContentModeScaleAspectFit;//设置内容填充模式    _logo.frame=logoRect;//设置控件大小和位置(相对于父控件的位置)    [self.view addSubview:_logo];//添加到KCMainViewControllerView

    

    //添加手机号码输入框    CGRect phoneNumberRect=CGRectMake(20, 320, 280, 30);

    _phoneNumber=[[UITextField alloc]initWithFrame:phoneNumberRect];

    _phoneNumber.borderStyle=UITextBorderStyleRoundedRect;//设置文本框的边框样式    [self.view addSubview:_phoneNumber];    

    //添加密码输入框    CGRect passwordRect=CGRectMake(20, 380, 280, 30);

    _password=[[UITextField alloc]initWithFrame:passwordRect];

    _password.borderStyle=UITextBorderStyleRoundedRect;

    [self.view addSubview:_password];    

    //添加登录按钮    CGRect loginButtonRect=CGRectMake(10, 440, 300, 25);

    _loginButton=[[UIButton alloc]initWithFrame:loginButtonRect];

    [_loginButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];//设置标题内容颜色    [_loginButton setTitle:@"登录" forState:UIControlStateNormal];//设置按钮标题    [_loginButton addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];//添加点击事件    [self.view addSubview:_loginButton];

}

 

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}

 

-(void)login:(UIButton *)btn{    if ([_phoneNumber.text isEqual:@"123"]&&[_password.text isEqual:@"456"]) {

        NSLog(@"登录成功!");

    }else{

        NSLog(@"登录失败!");

    }

}

 

@end

 

UIView

在这里我们需要对上面的代码一样解释,在弄清上面的代码之前我们不得不熟悉一个UIKit中最重要的类UIView

 

UIView就是指界面可见的控件元素,所有的控件最终都继承自UIViewUIView中还可以添加其他UIView(通过addSubView方法)

在一个iOS应用中必须有一个主窗口UIWindow(理论上也可以有多个UIWindow但是只有一个是主Window,而且只有主Window可以和用户交互),UIWindow也是继承自UIView,它拥有UIView的所有属性、方法;

UIWindow中必须有一个根控制器,这个控制器距离UIWindow是最近的;设置一个控制器为根控制器和直接通过addSubView添加控制器的视图(view属性)到window并不完全一样(例如如果仅仅添加控制器视图那么应用虽然可以显示但是不支持旋转);

UIViewController是视图控制器,主要用来控制UIView,在UIViewController内部有一个UIViewview属性);

在上面的代码中我们首先在应用程序开发加载完毕之后加载一个UIWindow对象,同时把我们的视图控制器KCMainController设置为UIWindow的根视图控制器,然后设置这个UIWindow为主窗口并可见。当主窗口设置为可见过程中会调用视图控制器的loadView方法来加载视图(注意视图控制器的loadView方法是延迟加载的,第一次调用视图控制器的view属性才会调用此方法;由于makeKeyAndVisible方法中会使用视图控制器的view属性所以此时会调用视图控制器的loadView方法),视图加载完之后调用viewDidLoad方法,在这个方法中我们添加登录相关控件并将这些控件加载到视图控制器KCMainViewController的视图view中。


最新回复 (0)
全部楼主
返回
发新帖