首先申明下,本文为笔者学习《Objective-C 基础教程》的笔记,并加入笔者自己的理解和归纳总结。
1. 异常
NSException
类表示异常。
打开支持异常特性。
异常关键字
@try
,定义代码块决定是否要抛出异常。@catch
,定义处理已抛出异常的代码块。接受一个异常,通常是NSException
类型。@finally
,定义无论是否抛出异常都会执行的代码块。@throw
,抛出异常。
异常处理格式
@try {
// 正常代码
} @catch (NSException *except) {
// 异常处理
} @catch (id value) {
// catch语句可以有多个
} @finally {
// 资源释放
}
抛出异常
抛出异常有两种方式。
- 使用
"@throw 异常名;"
来抛出异常。 NSException
调用raise
方法。
raise
只对NSException
有效,throw
可以用在其他对象上。
2. 选择器
@selector
定义选择器,responseToSelector:
方法判断对象是否包含该选择器,performSelector:
方法调用选择器。
@interface Shape : NSObject
- (void)draw;
@end
@implementation Shape
- (void)draw {
NSLog(@"Shape draw");
}
@end
int main(int argc, const char* argv[]) {
@autoreleasepool {
Shape *shape = [[Shape alloc] init];
[shape draw];
if ([shape respondsToSelector:@selector(draw)]) {
[shape performSelector:@selector(draw)];
} else {
NSLog(@"Not has draw");
}
if ([shape respondsToSelector:@selector(drawShape)]) {
[shape performSelector:@selector(drawShape)];
} else {
NSLog(@"Not has drawShape");
}
}
return 0;
}
输出
Shape draw
Shape draw
Not has drawShape
3. 代码块
代码块以^
(幂符号)定义。
int (^add_block)(int num1, int num2) = ^(int num1, int num2) { return num1 + num2; }
如果代码块没有参数,可以省略。
void (^void_block)() = ^{ NSLog(@"Hello World!"); }
代码块可以使用typedef
关键字
typedef int (^add_block)(int num1, int num2);
代码块可以使用本地变量,代码块会复制定义时的变量。如果要修改本地变量,可以使用_block
变量。
int main(int argc, const char* argv[]) {
@autoreleasepool {
int a = 11;
int b = 13;
void (^void_block)(void) = ^{ NSLog(@"Hello World!"); };
void_block();
typedef int (^add_block)(int num1, int num2);
add_block block = ^(int num1, int num2) { return num1 + num2; };
NSLog(@"%d + %d = %d", a, b, block(a, b));
int (^multiply)(void) = ^{ return a * b; };
NSLog(@"%d, %d, %d", a, b, multiply());
a = 15;
b = 17;
// multiply方法中a, b值未变化
NSLog(@"%d, %d, %d", a, b, multiply());
__block int c;
void (^minus)(int num1, int num2) = ^(int num1, int num2) { c = num1 - num2; };
minus(a, b);
NSLog(@"c = %d", c);
}
return 0;
}
输出
Hello World!
11 + 13 = 24
11, 13, 143
15, 17, 143
c = -2