天天看点

OC学习笔记(5)self与super

1、ASMath.h

#import <Foundation/Foundation.h>

@interface ASMath : NSObject
@property(nonatomic) double real;
@property(nonatomic) double imag;

-(id) initWithReal:(double)aReal imag:(double)aImag;
-(ASMath*) add:(ASMath*)aASMath;

@end
           

2、ASMath.m

#import "ASMath.h"

@implementation ASMath

-(id) initWithReal:(double)aReal imag:(double)aImag
{
    if(self = [super init])
    {
        _real = aReal;
        _imag = aImag;
    }
    return self;
}

-(ASMath*) add:(ASMath*)aASMath
{
    ASMath* result = [[ASMath alloc] init];
    result.real = self.real + aASMath.real;
    result.imag = self.imag + aASMath.imag;
    return [result autorelease];
}
@end

//self是实例方法的一个隐含参数,类似于C++和java的this
//self是指向当前对象的指针,它的值可以改变
//当一个方法调用类中的另一个方法时,self不可以省略,必须使用self指明消息的接受者

//super
//super是一个“编译器指示符”,它和self指向是相同的消息接收者,不同的是,super告诉编译器
//当向super发送消息时,要去父类的方法列表中查找对应的方法,而不是在本类里找
//super在编译之后就没有了,所以不可以改变super的值
           

3、main.m

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

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        ASMath *a = [[ASMath alloc] initWithReal:2 imag:4];
        ASMath *b = [[ASMath alloc] initWithReal:3 imag:6];
        ASMath *c = [a add:b];
        NSLog(@"%g %-gi",c.real,c.imag);
        
        [a release];
        [b release];
        [c release];
    }
    return 0;
}
           

打印结果

2014-12-19 15:52:55.529 test1[2625:100371] 5 10i