Objective C 快速入门学习二

Objective-C

类、对象、方法

1.编写一个复数类:

#import <Foundation/Foundation.h>
@interface Complex: NSObject //类声明,Complex继承NSObject { int iReal;//成员变量声明,在括号内 int iImag; } //成员函数声明,在括号外 -(void) print; -(void) setReal : (int) n; -(void)setImag : (int) d; @end //@interface ....@end区域完成类声明 @implementation Complex //成员函数实现部分 -(void) print //开头的负号(-)告诉编译器是实例方法, { NSLog(@"iReal = %i, iImag = %i \n", iReal, iImag);//"\n"和C/C++,表示换行 } -(void)setReal : (int) n // 返回值为void,输入参数为int n { iReal = n; } -(void)setImag: (int) d { iImag = d; }
@end //@implementation ... @end区域完成类成员函数实现

2.使用Complex类

int main(int argc, const char* argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //使用方法语法:  [ClassOrInstance   method]
    myComplex = [Complex alloc];
    myComplex = [Complex init];
    //可以合成一句 myComplex = [ [Complex alloc] init]
    //或者myComplex = [ Complex  new]

    [myComplex setReal : 1];//调用带参数的方法,实部设置为1
    [myComplex setImag : 2];

    [myComplex print];//调用print方法

    [myComplex release];//释放alloc的myComplex
    [pool drain];  
return 0; }

3.自己编程规范

(1).类首个字母大写

(2).函数和变量、对象首个字母小写

(3).变量加上类型修饰,可以区分对象