luky
luky

Reputation: 2370

Objective C pointer to pointer - how to distinguish passing nil vs not initialized variable set to nil

I have a method which accepts pointer to pointer param:

+(void)someMethod:(NSString*_Nullable*_Nullable)parsed;

Now, if i call this method and pass "nil" as parameter, and then i do the dereference inside of method like:

*parsed = soemthing;

I get crash BAD Access. Now question is, how to construct condition to distinguish passing "nil" vs passing not initilized variable like:

NSString* s; // this is technically nil too, but dereference works and doesn't crash
[someObj someMethod:&s];

to prevent the crash mentioned in first case.

Upvotes: 1

Views: 55

Answers (1)

ekscrypto
ekscrypto

Reputation: 3816

The solution is relatively simple, you should never pass an uninitialized variable. Consider doing this:

NSString *s = nil;
[someObj someMethod:&s];

Note the &s as you have declared someMethod to require a NSString **. By doing &s the parsed will always be defined, as the variable is obviously stored somewhere in memory. Its value, stored at *parsed will have been initialized to nil. You should then be able to do things like:

+(void)someMethod:(NSString* _Nullable *_Nullable)parsed {
    if( NULL != parsed ) {
        if( nil == *parsed ) {
            *parsed = @"Our variable *s will now be set!";
        }
    }
}

Upvotes: 2

Related Questions