Objective C 学习笔记(1) — 语法
objective c 是在C语言上扩展出来的,C的各种语法特性仍然适用。
#import 引用头文件,比#include 好的地方在于头文件只会包含一次,不用再写#ifdef 了.
NSLog Cocoa提供的函数库,统一以NS作为前缀,以示同C标准库的差别. NSLog与printf类似。
@”strings” @后接双引号字符串,代表NSString类型的字符序列,比普通的字符串有更多的用法。
main方法,同c语言一致 int main(int argc, const char * argv[]){return (0);}
面向对象.
id:对象指针类型
方法调用 [shape draw] ,调用shape对象的draw方法.shape 是id类型
//带参数的调用,green是参数
[circle setFillColor:green]
@interface 声明类接口
{
ShapeColor fillColor;
ShapeRect bounds;
}
- (void) setFillColor: (ShapeColor) fillColor;
- (void) setBounds: (ShapeRect) bounds;
- (void) draw;
@end
@implementation 实现类
- (void) setFillColor: ( ShapeColor ) c
{
fillColor = c;
}
@end //Circle
创建新实例, 调用类的new方法
构造方法
init
访问器 getter/setter
set方法需要带上set前缀,get方法不需要,保持跟属性一致即可。
@property 可以简化访问器. 声明同数据成员相同的属性,可以省去访问器方法的编写
@property (选项) 类型 名字;选项包括readwrite/readonly/assign/retain/copy/atomicity等。
在实现中需要用@synthesize让编译器获取实现代码
之后可以用.来引用属性来读取和写入,而不需要调用方法。
继承/组合
super 访问父类
self
@class 声明使用的类,可以不需要#import a.h, 避免循环引用
静态方法, 以+开头
+ (void) instance;
@protocol 协议,类似其他语言中的接口。 遵循协议就必须实现其中规定的方法。
一个类可以同时遵循多种协议。还可以用@optional指定非必须实现的方法
- (void) encodeWithCoder: (NSCoder *) aCoder;
- (id) initWithCoder: (NScoder *) aDecoder;
@end
@interface Car: NSObject
{
}
@end






