LoginSignup
5
5

More than 5 years have passed since last update.

NSMutableArrayオブジェクトにnilを追加するとエラーになる件

Last updated at Posted at 2014-02-19

背景

引数の数によらず、一定の数だけ配列の要素数を確保したいと思っていた。
for文で、一定数に不足した分だけ仮に@""か0を代入する方針だった。

課題

[確保したい一定数] - [現時点の要素数]の分だけ、@""か0を代入したかったのでこのようにやったらエラー

        for( NSInteger i = [mutableArray count]; i < 3; i++){
            [mutableArray addObject:0];
        }

エラーメッセージは
-[__NSArrayM insertObject:atIndex:]: object cannot be nil

解決方針

このようにやったらうまくいった。

        for( NSInteger i = [mutableArray count]; i < 3; i++){
            [mutableArray addObject:@0];
 }
        for( NSInteger i = [mutableArray count]; i < 3; i++){
            NSString *str = [NSString stringWithFormat:@""];
            [mutableArray addObject:str];
 }

参考

激しく勉強になった
nilにまつわるエトセトラ

5
5
9

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
5
5