`
阿尔萨斯
  • 浏览: 4108010 次
社区版块
存档分类
最新评论

OC-对象方法/类方法/self/super(1)

 
阅读更多

1.在Objective-C中,对象方法类比于Java的静态方法和对象方法.代码如下

-声明

  2014-06-05 10:18:50
#import <Foundation/Foundation.h>

@interface Student : NSObject

//每个学生拥有学习的行为
+ (void) study;

// spendMoney: 称为方法名
//(int)price 称为参数
//(void)称为返回参数,必须用括号括起来
- (void) spendMoney:(int)price;

@end

-定义

#import "Student.h"

@implementation Student

+ (void) study
{
    NSLog(@"All student can study!");
}

- (void) spendMoney:(int)price
{
    NSLog(@"student spend %d yuan!",price);
}

@end

-调用

//类方法调用
[Student study];
//匿名对象方法的调用
[[[Student alloc] init] spendMonery:20];

2.self/super:作为特殊的内置指针,谁调用指向谁(类/对象)

Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject
{
    @public
    int _price;
}
//每个学生拥有学习的行为
+ (void) study;

// spendMoney: 称为方法名
//(int)price 称为参数
//(void)称为返回参数,必须用括号括起来
- (void) spendMoney:(int)price;

@end

Student.m

#import "Student.h"

@implementation Student

+ (void) study
{
    NSLog(@"All student can study!");
}

- (void) spendMoney:(int)price
{
    //同样,类调用时self指向的是类,对象调用时self指向的是对象,
    //self同时可以指向类和对象的属性 也可以作为方法的调用的指针
    //当指向属性时,无论是其本身还是父类的属性.
    //因为在内存加载的时候首先会把对象的所有属性加载进来
    self->_price=price;
    NSLog(@"student spend %d yuan!",self->_price);
}

@end

Academican.h

#import <Foundation/Foundation.h>
#import "Student.h"

@interface Academician : Student

@end


Academican.m

#import "Academician.h"

@implementation Academician

+ (void) study
{
    //1.当外部调用为对象时 super指向的是对象,当外部调用为类时 super指向的是类
    //2.super只能用来调用方法 不能用来作为指向属性的指针即super->_price 是 错误的 
    [super study];
    NSLog(@"All Academician can study!");
}

- (void) spendMoney:(int)price
{
    NSLog(@"Academician spend %d yuan!",price);
}

@end



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics