美文网首页
OC学习之方法和函数区别

OC学习之方法和函数区别

作者: 龙马君 | 来源:发表于2016-02-25 11:40 被阅读1138次

    方法和函数区别

    方法

    OC的方法,是指类方法和对象方法,只能在@interface和@end之间声明,在@implementation和@end之间定义。
    声明和实现:
    类方法以+号开头,对象方法以-号开头。

    // MyTestClass.h
    @interface MyTestClass : NSObject
    // 声明方法,类方法用+;对象方法用-;
    +(void)createClass;
    -(void)show;
    @end
    
    // MyTestClass.m
    @implementation MyTestClass
    +(void)createClass
    {
        
    }
    
    -(void)show
    {
        
    }
    @end
    

    new 是旧版本的用法,实际上也是调用alloc init的方式

    方法调用方式,需要使用中括号,[]

    // 方法调用需要使用[]
    MyTestClass* class1 = [MyTestClass new];
    MyTestClass* class2 = [[MyTestClass alloc] init];
    [class1 show];  // 对象方法调用
    [class2 show];
    
    [MyTestClass createClass]; // 类方法调用
    

    函数

    函数就是C语言中的函数了,可以在C和OC中声明和定义(除@interface和@end之间)
    函数不依赖于对象;

    // 定义一个函数
    int max(int x, int y){
        return x > y ? x : y;
    }
    

    相关文章

      网友评论

          本文标题:OC学习之方法和函数区别

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