Roman Barzyczak
Roman Barzyczak

Reputation: 3813

In Objective-c what I should use to return that parameter can't be nil?

I know that I can return that parameter can't be nil by NSError or throw NSException, but what is the best option to inform that parameter can't be nil in objective-c ?

Upvotes: 2

Views: 174

Answers (3)

Avt
Avt

Reputation: 17043

To check at compile time use

__attribute__ with nonnull

Example, first and second parameters should not be null:

extern void * my_memcpy (void *dest, const void *src, size_t len) 
__attribute__((nonnull (1, 2)));

The nonnull attribute specifies that some function parameters should be non-null pointers. Using nonnull encodes expectations about values into an explicit contract, which can help catch any NULL pointer bugs lurking in any calling code. Remember: compile-time errors ≫ run-time errors.

Read more here

Upvotes: 0

Droppy
Droppy

Reputation: 9721

You could use NSAssert(), which will only fire in builds where NS_BLOCK_ASSERTIONS is not defined:

- (void)someMethodWithParam:(id)someParam {
    NSAssert(someParam, @"someParam cannot be nil");
    ...
}

That will pretty much restrict the checking to you, and fellow developers, but if you want it to persist, regardless of build, then an NSException is best:

- (void)someMethodWithParam:(id)someParam {
    if (!someParam) {
        [NSException raise:@"MyException" format:@"someParam cannot be nil"];
    }
    ...
}

Upvotes: 0

Wain
Wain

Reputation: 119021

Documentation.

Use assertions to raise exceptions during development.

Return an NSError too (though it should hopefully never happen by the time you get to production).

Upvotes: 1

Related Questions