02.OC方法

作者: 心扬 | 来源:发表于2018-06-21 22:42 被阅读5次

    定义方法

    在OC中,定义一个方法,分为声明和实现,声明要写在@interface中,而实现要写在@implementation

    编写方法的规律总结

    1. 确定函数名称
    2. 确定形参
    3. 确定返回值
    4. 确定返回值类型

    方法的声明

    • 无参无返回值对象方法
    @interface User : NSObject
    {
        @public
        char * _name;
        int _age;
    }
    - (void)about;
    @end
    
    • 无参有返回值的对象方法
    - (char *) write;
    
    • 有参有返回值对象方法
    - (int) call: (int) number;
    
    • 多个参数有返回值对象方法
    - (int) send:(int)number :(char *) content;
    
    • 带标签的多参数对象方法
    - (int) sendMsgWithNum:(int)number andContent:(char *) content;
    

    方法的实现

    • 无参无返回值对象方法
    @implementation User
    - (void)about{
        NSLog(@"about方法实现");
    }
    @end
    
    • 无参有返回值的对象方法
    - (char *) write{
        return "hello";
    }
    
    • 多个参数有返回值对象方法
    - (int) send:(int)number :(char *) content{
        NSLog(@"发送短信【%s】给%i",content,number);
        return 1;
    }
    
    • 带标签的多参数对象方法
    - (int) sendMsgWithNum:(int)number andContent:(char *) content{
        NSLog(@"发送短信【%s】给%i",content,number);
        return 1;
    }
    

    调用方法(给对象发送消息)

    • 调用无参无返回值的对象方法
    User * user = [User new];
    [user about];
    
    • 无参有返回值的对象方法
    char * str = [user write];
    NSLog(@"write=%s",str);
    
    • 有参数有返回值的对象方法
    int result = [user call:123];
    NSLog(@"返回值 %i",result);
    
    • 多个参数有返回值对象方法
    result = [user send:123 :"hello"];
    NSLog(@"发送短信结果 %i",result);
    
    • 带标签的多参数对象方法
    result = [user sendMsgWithNum:1234 andContent:"world"];
    NSLog(@"发送短信结果 %i",result);
    

    类方法的声明和实现

    • 类方法的声明
    + (int)caculate:(int)value1 addAnother:(int)value2;
    
    • 类方法的实现
    + (int)caculate:(int)value1 addAnother:(int)value2{
        return value1 + value2;
    }
    
    • 类方法的调用
    result = [User caculate:1 addAnother:2];
    NSLog(@"计算结果 %i",result);
    
    

    如果声明的是对象方法,那么就必须实现对象方法;如果声明的是类方法,就必须实现类方法

    类方法与对象方法的区别

    1. 对象方法以- 开头,类方法以+开头
    2. 对象方法必须用对象调用,类方法必须用类调用
    3. 对象方法中可以直接访问属性(成员变量),类方法中能直接访问属性
    4. 调用类方法比调用对象方法效率高
    5. 对象方法中可以直接调用类方法,类方法中要通过对象调用对象方法,类方法中可以直接调用类方法,对象方法中可以直接调用对象方法

    类方法的使用场景

    • 方法中没有使用到属性,尽量使用类方法,因为类方法的执行效率高
    • 类方法一般用于定义工具方法

    相关文章

      网友评论

        本文标题:02.OC方法

        本文链接:https://www.haomeiwen.com/subject/iwchyftx.html