Objective-C 基础(二)

Methods, Messages, and Selectors

Undeclared Methods
在ARC机制下,LLVM编译器不允许给对象发送没定义的方法,强制执行会报runtime error 错误并且编译不通过,MRR机制下则只会抛警告错误;

Pointing to Objects
id 类型相当于(NSObject *),可以指向任何类型对象,

NSMutableArray 可变数组, 属于NSArray的子类,是数组大小可变的一种特殊数组,

NSArray *anotherArray = [NSMutableArray array];
// This mutable-only method call will cause an error
[anotherArray addObject:@"Hello World"];

NSArray *standardArray = [NSArray array];
NSMutableArray *mutableArray;
// This line produces a warning
mutableArray = standardArray;
// This will bomb at runtime
[mutableArray addObject:@"Hello World"];

 Declaring Methods
- (void) setMake:(NSString *) aMake andModel:(NSString *) aModelandYear: (int) aYear;
- (void) printCarInfo;
- (int) year;

Inheriting Methods 方法继承
子类继承拥有父类所有方法,可以覆盖父类的方法,但不能取消父类的方法;

 Implementing Methods 方法实现  
if(self)表示如果self不是指的空地址

nil 可以执行任何方法,其返回值仍然是 nil.

 方法重载

重载要么改变参数的名字,要么增加参数,否则相同数量的参数,只改变参数的类型将无法编译。

 

Class Methods 类方法
+ (NSString *) motto;
类方法不能访问对象里的变量,只能被类所调用;类方法可以访问Singletons(静态分配实体,如 [UIApplication sharedApplication] 、[UIDevice currentDevice]);类方法可以直接与内存管理策略关联,如[NSArray array] 等效于[[NSArray alloc]init];

Fast Enumeration 快速枚举
NSArray *colors = [NSArray arrayWithObjects:

@"Black", @"Silver", @"Gray", nil];
for (NSString *color in colors)
printf("Consider buying a %s car", [color UTF8String]);

Note
Use caution when using a method such as arrayWithObjects: or
dictionaryWithKeysAndValues:. These can be unnecessarily error-prone. A common
error occurs when one of the mid-list arguments evaluates to nil. This is especially easy to
miss for NSDictionarys, which can have missing key-value pairs as a result. Developers
often use this method with instance variables without first checking whether these values
are non-nil, which can cause runtime errors. Another common mistake is to forget the final
“sentinel” nil at the end of your arguments. This missing nil may not be caught at compile
time but will cause runtime errors as well.

Class Hierarchy类继承



posted @ 2012-12-29 22:23  Ivan的coding世界  阅读(163)  评论(0编辑  收藏  举报