iOS @try @catch @finally 用法
2016-12-20 本文已影响206人
hehtao
音频caf 转 mp3 遇到一段神奇的代码如下:
#pragma mark - caf转mp3
- (void)audio_PCMtoMP3Result:(void(^)(NSData *))result
{
@try {
int read, write;
FILE *pcm = fopen([self.cafPathStr cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
fseek(pcm, 4*1024, SEEK_CUR); //skip file header
FILE *mp3 = fopen([self.mp3PathStr cStringUsingEncoding:1], "wb"); //output 输出生成的Mp3文件位置
const int PCM_SIZE = 8192;
const int MP3_SIZE = 8192;
short int pcm_buffer[PCM_SIZE*2];
unsigned char mp3_buffer[MP3_SIZE];
lame_t lame = lame_init();
lame_set_in_samplerate(lame, 11025.0);
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
do {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wshorten-64-to-32"
read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
#pragma clang diagnostic pop
if (read == 0)
write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
else
write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
fwrite(mp3_buffer, write, 1, mp3);
} while (read != 0);
lame_close(lame);
fclose(mp3);
fclose(pcm);
}
@catch (NSException *exception) {
NSLog(@"%@",[exception description]);
}
@finally {
NSLog(@"MP3生成成功: %@",self.mp3PathStr);
result([NSData dataWithContentsOfFile:self.mp3PathStr]);
}
}
@try @catch @finally 是个什么鬼东西?
大概分析一下代码逻辑如下:
@try {
... 逻辑处理
...执行的代码,其中可能有异常。一旦发现异常,则立即跳到catch执行。否则不会执行catch里面的内容
}
@catch {
... 异常捕捉
...除非try里面执行代码发生了异常,否则这里的代码不会执行
}
@finally{
... 逻辑执行结果
...不管什么情况都会执行,包括try catch 里面用了return ,可以理解为只要执行了try或者catch,就一定会执行 finally
}