LoginSignup
4
2

More than 5 years have passed since last update.

Objective-Cにてtry-catchした時に変数がmutableになってしまう問題の解決方法

Last updated at Posted at 2017-02-07

困ったこと

こんなコードがあるときにtry-catchを入れたくなりますよね。

NSString *const name = [self getNameMethodMayCauseException];    // 例外が発生するかもしれないメソッドや処理
[self otherMethodWithName:name];

するとこんな感じにnameが意味もなくmutableになってしまいます。

NSString *name = nil; // immutableでありたい:(
@try {
    name = [self getNameMethodMayCauseException];    // 例外が発生するかもしれないメソッドや処理
} @catch (NSException *exception) {
    name = nil;
}
[self otherMethodWithName:name];

解決法

どうにかimmutableにしたいと考えた結果、blocksを利用することでそれっぽくなりました。

// immutable :)
NSString *const name = ^NSString*(){
    @try {
        return [self getNameMethodMayCauseException];    // 例外が発生するかもしれないメソッドや処理
    } @catch (NSException *exception) {
        return nil;
    }
}();
[self otherMethodWithName:name];
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2