zoukankan      html  css  js  c++  java
  • Objective C 快速入门学习五

     
    
    
    <一>继承和多态
    @class   Complex  声明类(同C++)
    子类函数成员 super 访问父类 
    
    同C++类似
    1.通过继承 在子类中添加新方法
    2.通过继承 在子类中添加新成员
    3.通过继承 实现多态(实现比较简单,通过Id通用类型作为父类)
    4.重载
    5.抽象类abstract作用:创建子类更容易;提供了处理所有派生子类的公共接口;抽象方法制定了标准协议,规范子类必须实现。
    6.通用类型id,编译时不会做类型检查,在运行时才会动态绑定具体类型,指出错误。
      静态类型在编译阶段就会指出错我,另外,可以提高程序的可读性。
    
    7.处理动态类型若干方法
    mySquare是Square类的实例。
    [Square class]  //从Square类获得类对象
    [mySquare class]  //从mySquare对象获得其所属类
    [obj1 class] == [obj2 class]  //判定两个对象是否属于同一个类
    [mySquare is MemberOf: [Square class]]  //判定mySquare是不是Square的实例
    @selector (alloc)  //为alloc方法生成1个SEL类型的值
    [Square respondsTo @selcetor (alloc)] == YES  //判断Square类是否响应alloc类方法
    [Square instanceRespondToSelector: @selector(action)]  //查看Square的实例是否响应action方法
    eg:
    if([Square instanceRespondToSelector: @selector(action)] == YES)
    [mySquare performSelector: @selector (action)]   //应用action方法
    
    [Square isSubclassOfClass: [Rectangle class]] == YES   //判断Square是否为Rectangle子类
    
    
    <二>@try异常处理
    -(void)action
    {
      ...
     if(数组越界)
      NSException *e = [NSException exceptionWithName:@"out of array" reason:@"address is invalid" userInfo: nil]
      @throw e;//抛出异常
    }
    
    @try
    {
      [mySquare  action];//尝试执行mySquare action方法
    }
    
    @catch(NSException *exception)
    {  //捕捉异常,也可以派生NSException子类,重新定义具体细节
      NSLog(@"Caught %@%@", [exception name], [exception reason]);//产生异常的名称和原因
    }
    @finally 
    {//无论异常是否发生,都必须执行
     <代码块>
    }
    
    <三>协议和分类
    分类可以扩展类的方法,无需创建子类,无需访问类的源代码,但是它会影响到子类。
    @interface Square (MathOps)
    -(void) print;//增加新方法,与协议默认不同,不强制实现
    @end
    
    协议是多个类共享的一个方法列表,与抽象类的抽象方法类似,子类必须都要实现该方法。
    
    @protocal <NSCoding>//NSCoding协议
    -(void)copyWithZone;//默认是必须实现
    @optional //表示可选项,不强制该协议的使用者实现该函数print
    -(void) print;
    @required //表示必须实现cout
    -(void) cout;
    @
    
    @protocal <NSCopying>//NSCopying协议
    -(void)copy;
    @end
    
    @interface AddressBook: NSObject<NSCopying, NSCoding>//可以采用多个协议
    @interface Square (MathOps)<NSCopying, NSCoding>//分类也可以采用协议
  • 相关阅读:
    在Ubuntu18.04.2LTS上安装搜狗输入法
    生活点滴:java基础知识细化
    乘风破浪:LeetCode真题_041_First Missing Positive
    乘风破浪:LeetCode真题_040_Combination Sum II
    乘风破浪:LeetCode真题_039_Combination Sum
    乘风破浪:LeetCode真题_038_Count and Say
    乘风破浪:LeetCode真题_037_Sudoku Solver
    乘风破浪:LeetCode真题_036_Valid Sudoku
    乘风破浪:LeetCode真题_035_Search Insert Position
    乘风破浪:LeetCode真题_034_Find First and Last Position of Element in Sorted Array
  • 原文地址:https://www.cnblogs.com/welen/p/3854847.html
Copyright © 2011-2022 走看看