7

最初のパラメーターが/の場合、 は 2 番目のパラメーターif-statement&& operatorチェックしますか?falseNO

以下はクラッシュする可能性がありますか?

NSDictionary *someRemoteData = [rawJson valueForKey:@"data"];
if( [someRemoteData isKindOfClass:[NSDictionary class]] && someRemoteData.count > 0 ){
    //..do something
}

単純な「はい」または「いいえ」の答えではなく、理由を説明してください。

4

3 に答える 3

21

No, it does not evaluate the expression after learning that the answer is going to be NO. This is called short-circuiting, and it is an essential part of evaluating boolean expressions in C, C++, Objective C, and other languages with similar syntax. The conditions are evaluated left to right, making the evaluation scheme predictable.

The same rule applies to the || operator: as soon as the code knows that the value is YES, the evaluation stops.

Short-circuiting lets you guard against invalid evaluation in a single composite expression, rather than opting for an if statement. For example,

if (index >= 0 && index < Length && array[index] == 42)

would have resulted in undefined behavior if it were not for short-circuiting. But since the evaluation skips evaluation of array[index] when index is invalid, the above expression is legal.

于 2013-01-15T15:29:28.370 に答える
3

Objective-C は遅延評価を使用します。これは、左のオペランドのみが評価されることを意味します。

于 2013-01-15T15:41:06.463 に答える
0

いいえ、違います。最初のステートメントが失敗した場合、2番目のステートメントはチェックされないため、たとえばこれを行うことができ(ArrayList != null && ArrayList.size() > 0)、変数が初期化されていない場合にエラーが発生することはありません。

于 2013-01-15T15:31:31.043 に答える