码迷,mamicode.com
首页 > 其他好文 > 详细

OC-类方法

时间:2015-11-07 21:57:23      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:

 类方法

1. 基本概念

直接可以用类名来执行的方法(类本身会在内存中占据存储空间,里面有类\对象方法列表)

2. 类方法和对象方法对比

1)  对象方法

  • 以减号-开头
  • 只能让对象调用,没有对象,这个方法根本不可能被执行
  • 对象方法能访问实例变量(成员变量)

2)  类方法

  • 以加号+开头
  • 只能用类名调用,对象不能调用
  • 类方法中不能访问实例变量(成员变量)
  • 使用场合:当不需要访问成员变量的时候,尽量用类方法

3) 类方法和对象方法可以同名

 

#import <Foundation/Foundation.h>
@interface Person : NSOvject
//类方法
{
    int age;
}
+ (void)printClassName;
@end

@implementation Person
+ (void)printClassName
{
    //error : instance variable ‘age‘ accessed in class method
    //实例变量age不能在类方法中访问,即类方法不能访问成员变量
    NSLog(@"这个类叫做Person--%d", age);
}
- (void)test
{
    NSLog(@"调用了test方法");
    [Person test];//可以调用方法
}
+ (void)test
{
    NSLog(@"lei");
    //[Person test]; 会引发死循环
}
@end

int main()
{
    Person *p = [Person new];

    [p printClassName];

    [Person test];//只能用类调用类方法  

    return 0;
}

 

OC-类方法

标签:

原文地址:http://www.cnblogs.com/IDRI/p/4946084.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!