2

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 ?

Roman Barzyczak
  • 3,785
  • 1
  • 30
  • 44

3 Answers3

1

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).

Wain
  • 118,658
  • 15
  • 128
  • 151
0

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"];
    }
    ...
}
Droppy
  • 9,691
  • 1
  • 20
  • 27
0

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

Avt
  • 16,927
  • 4
  • 52
  • 72