有时你会看到一段 iOS - Objective-C 代码使用了 Try/Catch 结构。
例如这个例子来自:http ://docs.xrtml.org/2-1-0/pubsub/ios/ortcclient.html
- (void)viewDidLoad
{
[super viewDidLoad];
// Instantiate OrtcClient
ortcClient = [OrtcClient OrtcClientWithConfig:self];
// Post permissions
@try {
NSMutableDictionary* myPermissions = [[NSMutableDictionary alloc] init];
[myPermissions setObject:@"w" forKey:@"channel1"];
[myPermissions setObject:@"w" forKey:@"channel2"];
[myPermissions setObject:@"r" forKey:@"channelread"];
BOOL result = [ortcClient saveAuthentication:@"http://ortc-developers.realtime.co/server/2.1/" isCLuster:YES authenticationToken:@"myAuthenticationToken" authenticationTokenIsPrivate:NO applicationKey:@"myApplicationKey" timeToLive:1800 privateKey:@"myPrivateKey" permissions:myPermissions];
if (result) {
// Permissions correctly posted
}
else {
// Unable to post permissions
}
}
@catch (NSException* exception) {
// Exception posting permissions
}
// Set connection properties
[ortcClient setConnectionMetadata:@"clientConnMeta"];
[ortcClient setClusterUrl:@"http://ortc-developers.realtime.co/server/2.1/"];
// Connect
[ortcClient connect:@"myApplicationKey" authenticationToken:@"myAuthenticationToken"];
}
为什么要使用这样的结构,难道你不能saveAuthentication:isCLuster:authenticationToken:...
像“常规”Cocoa-Touch 代码那样检查来自方法的 NSError(间接)返回吗?例如读取 JSON 时:
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error == nil){
NSLog(@"%@", result);
}else{
NSLog(@"%@", [error localizedDescription]);
}