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 ?
3 Answers
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).

- 118,658
- 15
- 128
- 151
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"];
}
...
}

- 9,691
- 1
- 20
- 27
-
NSParameterAssert would be more appropriate here – jrturton Apr 30 '14 at 11:38
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

- 16,927
- 4
- 52
- 72