Objective-C 30分钟入门教程
我第一次看OC觉得这个语言的语法有些怪异,为什么充满了@符号,[]符号,函数调用没有()这个,但是面向对象的高级语言也不外乎类,接口,多态,封装,继承等概念。下面会把OC里面的一些定义与Java,C++作对比,让有其他面向对象语言的同学可以快速的了解OC是个神马语言。
1.类定义
类用@interface定义,而不是@class,相当于Java中的class了。而Object-C中接口(Java中的接口)是用@protocol(下面有介绍)表示。
头文件,与c++的头文件类似
1 #import <Foundation/Foundation.h> 2 @interface Fraction : NSObject 3 //成员变量 4 { 5 @protected 6 int numerator; 7 int denominator; 8 } 9 //类方法 10 -(void) print; 11 //多参数函数 12 -(id)initSetNum:(int) n over:(int) d; 13 -(id) init; 14 @end
实现.m文件(相当于c中的.cpp)
1 #import "Fraction.h" 2 3 @implementation Fraction 4 5 -(void) print { 6 NSLog(@"print"); 7 } 8 9 -(id)init{ 10 self = [super init]; 11 if (self != nil) { 12 self->denominator = 1; 13 self->numerator = 1; 14 } 15 return self; 16 } 17 -(void)set:(int)n over:(int)d { 18 self->denominator = d; 19 self->numerator = n; 20 } 21 22 @end
init模板
1 -(id)init{ 2 self = [super init]; 3 if (self) { 4 //do init 5 } 6 return self; 7 }
2.访问权限
实例变量的作用域
- @protected: 实例变量可被该类和子类中定义的方法直接访问。接口部分定义的实例变量是此作用域
- @private: 只能被定义在此类中的方法直接访问。定义在实现部分的实例变量默认为此作用域
- @public: 可被此类中的方法、子类或其他类直接方法(访问方法见下面点语法)
- @package: 对于64位镜像,可以在实现改类的镜像中的任何地方访问此实例变量(不了解,没用过)
@property作用域
@property只在@interface中使用,是默认的@protected权限
方法的作用域
@protected,@private,@public,@package不适用实例方法,在@interface中定义的方法都是@public方法
私有方法
1.不在@interface中声明,直接写到@implemention里。
2.写在空分类中。
3.@property和@synthesize
语法
@property(attribute1, attribute2, ...) type name;
作用1:生成成员变量的get和set方法
1 @interface Fraction : NSObject 2 @property int numerator, denominator; 3 -(void)print; 4 @end
1 @implementation Fraction 2 @synthesize numerator = _abc, denominator = _def; 3 4 -(void) print { 5 self->_abc = 12; 6 self->_def = 30; 7 } 8 @end