Objective C 学习笔记(1) — 语法

Posted by reedboat on Jun 8, 2011 in 编程 |

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类型

[circle draw]
//带参数的调用,green是参数
[circle setFillColor:green]

@interface 声明类接口 

@interface Circle :NSObject
{
    ShapeColor fillColor;
    ShapeRect bounds;
}
- (void) setFillColor: (ShapeColor) fillColor;
- (void) setBounds: (ShapeRect) bounds;
- (void) draw;
@end

@implementation 实现类

@implementation Circle. 实现代码中省略掉了self self->fillColor = c;
- (void) setFillColor: ( ShapeColor ) c
{
    fillColor = c;
}
@end //Circle

创建新实例, 调用类的new方法

[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指定非必须实现的方法

@protocol NSCoding
 
- (void) encodeWithCoder: (NSCoder *) aCoder;
- (id) initWithCoder: (NScoder *) aDecoder;



@end

@interface Car: NSObject
{
}

@end

 

关于作者
reedboat, 每讯网, 研发经理
执着的技术人,完美的追求者。
PHP、JS职业攻城师。
SNS、SCM、IOS、敏捷开发、推荐算法…

无觅相关文章插件,快速提升流量

Tags:

Reply

使用新浪微博登陆

Copyright © 2012 苇叶舟 All rights reserved. Theme by Laptop Geek.