CG@CPPBLOG

/*=========================================*/
随笔 - 76, 文章 - 39, 评论 - 137, 引用 - 0
数据加载中……

用OBJC编程 0-简介 & .1 定义类

<Programming with Objective-C>-0-Introduction

OBJC是OSX和IOS的主要编程语言,它是C的超集,提供了面向对象的特性和动态运行时类型信息。OBJC继承了C的语法,基本数据类型和流程控制,附加了定义类和方法的语法。也为动态类型绑定提供了语言级别的支持。

<Programming with Objective-C>-1-Defining Classes

可变性决定值是否可以更改
一些类定义对象是immutable的,意味着对象的内容不可被其它对象改变。NSString和NSNumber是immutable的

一些immutable类页游mutable版本。比如NSString的NSMutableString。

尽管NSString和NSMutableString是不同的类,它们有非常多的相似之处

从另一个类继承
从另一个类继承,子类继承了父类所有的行为和属性。也可以定义自己的behavior和properties,或者override父类的behavior

NSMutableString继承于NSString,因此拥有所有NSString的功能,也增加了append,insert,replace,delete substring等方法

根类提供基本功能
如果你定义一个自己的类,应该至少继承于NSObject

类的接口定义

基本语法
1 @interface SimpleClass : NSObject
2 
3 @end

Properties控制访问一个对象的值
@interface Person : NSObject

@property NSString 
*firstName; // 对象用指针
@property NSString *lastName;
@property NSNumber 
*yearOfBirth;
@property 
int yearOfBirth_1; // 用基本类型

@end

Property属性指明数据的可访问性和存储情况
@interface Person : NSObject
@property (
readonly) NSString* firstName;
@property (
readonly) NSString* lastName;
@end

方法定义
-(void)someMethod;
前面的 - 号表示这是一个实例方法

方法可以带参数

-(void)someMethodWithValue:(SomeType)value;

可以有多个参数
-(void)someMethodWithFirstValue:(SomeType)value1 secondValue:(AnotherType)value2;
secondValue 是第二个参数签名的一部分

因此,下面的函数签名不同:
-(void)someMethodWithFirstValue:(SomeType)info1 anotherValue:(AnotherType)info2;
-(void)someMethodWithFirstValue:(SomeType)info1 secondValue:(YetAnotherType)onfo2;

类名称必须唯一
类名必须唯一,甚至和库或者框架里的类也不能重名,建议使用三个字符的前缀。
两个字母前缀,如NS,UI,已经被Apple保留

类的实现

基本语法

#import "XYZPerson.h"

@implementation XYZPerson

@end

实现方法

// interface like this
@interface XYZPerson : NSObject
- (void)sayHello;
@end

// implementation like this

@implementation XYZPerson
- (void)sayHello{
   NSLog(
@"Hello, World!");
}
@end

类也是一个对象

在OBJC里,类自己也是一个Class类型的对象。类类型不能通过声明的语法定义property,但是它可以接收消息。

类类型的方法的典型用途是工厂方法,用来进行对象的分配和初始化,如NSString的工厂方法

+(id)string;
+(id)stringWithString:(NSString *)aString;
+(id)stringWithFormat:(NSString *)format,.. . ;
+(id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)end error:(NSError **)error;
+(id)stringWithCString:(const char*)cString encoding:(NSStringEncoding)enc;

+ 号表示这是一个类的方法

posted on 2013-11-19 18:34 cuigang 阅读(619) 评论(0)  编辑 收藏 引用 所属分类: OBJC


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理