0

I trying fill array from existing filled array but sometimes get this error:

*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[4830]

Exception caused by this code line:

 NSArray *result = [NSArray arrayWithArray:self.testerLog];

testerLog is NSMutableArray and I use it for collect logs from App. tester logs filled next way:

[self.testerLog addObject:[NSString stringWithFormat:@"%@: %@ \n", [NSDate date], logRecord]];

How it could happens? No exception when I add object to testerLog and fail when trying fill array from this filled array?

Edit: About initializing testerLog. Here is code of testerLog method:

- (NSMutableArray *)testerLog {
    if (!_testerLog) {
        _testerLog = [NSMutableArray array];
    }

    return _testerLog;
}

So I think it should be not nil.

UPDATE: I forget to say that method that add NSString to testerLog may called from several threads;

4

2 に答える 2

1

投稿したゲッターはスレッドセーフではありません。同等のスレッド セーフな getter を取得するには、代わりに次のコードを使用します。

-(NSMutableArray *)testerLog {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        // If you're not using ARC you most definitely want to retain the array!
        // _testerLog = [[NSMutableArray array] retain]; 

        // If you're using ARC you should just assign
        _testerLog = [NSMutableArray array];
    });

    return _testerLog;
}

dispatch_once 呼び出しにより、どのようなコードを入れても、アプリの存続期間中に (スレッドセーフな方法で) 1 回だけ実行されるようになります。staticonceTokenは、特定のブロックを識別するものです。特定のケースでは、このゲッターを実行するスレッドの数に関係なく、配列が一度だけインスタンス化されることが保証されるため、これは便利です。

非 ARC のみ: 保持は、このメソッドの実行後も配列を存続させたいためです (これも、ARC を使用していない場合のみ)。

nilまた、何らかの論理エラーがあったことを意味するため、どこかに値が表示されることを期待していない場合は、assertions を使用してください。以下は、それらの使用方法の例です。

assert(self.testerLog != nil);
NSArray *result = [NSArray arrayWithArray:self.testerLog];
于 2013-01-18T11:28:33.407 に答える
0

testerLog 配列が正しく初期化されていることを確認してください。それはゼロであり、それがあなたの問題を引き起こしています!

有効な NSString を testerLog 配列に追加しようとしているため、 addObject がエラーをスローしていない可能性があります。オブジェクトを追加した行の直後に self.testerLog で NSLog を実行してみてください。期待どおりに testerLog 配列が正しく出力されていることを確認してください。

于 2013-01-18T07:15:01.443 に答える