質問

- (void)playAlarmSound:(NSTimer *)theTimer {
    static SystemSoundID soundID/* = 0 */; // ?
    if (!soundID) {
        soundID = [Utilities createSystemSoundIDFromFile:@"beep" ofType:@"caf"];
    }
    ...
}

SystemsoundID(UINT32はどれですか)は自動的に割り当てられていますか?または、明示的に割り当てる必要がありますか?私はこのようにそれをしなければなりません、そして、私がただしている場合にコンパイルされないため、ユーティリティメソッドによってそれが初期化されていないかどうかを確認するためにテストする必要があります static SystemSoundID soundID = [Utilities createSystemSoundIDFromFile:@"beep" ofType:@"caf"];. 。最初はnullに割り当てようとしましたが、ポインターではないことに気付いたので、とにかく、 = 0 そこにあるのですか、それとも冗長ですか?

役に立ちましたか?

解決

This question doesn't involve any objective-c features, so the answer is found in the c standard.

C99, section §6.7.8, paragraph 10:

If an object that has static storage duration is not initialized explicitly, then:

...

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

UInt32 (which itself is just uint32_t) is an arithmetic type. Hence, initialized to zero.

他のヒント

This doesn't have anything to do with the type — it has to do with storage class. In C, static and global variables are automatically initialized to 0. Ordinary local (auto) variables aren't automatically initialized, so you have to do it yourself or they'll contain garbage.

I believe objective-c follows the same rules as C for this.

static and global variables are initialized to 0 while local (i.e. auto) variables are not initialized and can start with an unpredictable value.

That said, it doesn't hurt to explicitly initialize the value to 0.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top