Pregunta

I'm wondering about whether or not this is good practice:

I have a method that takes in parameters and a callback block, let's say something along the lines of:

-(void)loginWithUsername:(NSString *)username andPassword:(NSString *)password withCompletion:(LoginManagerCompletionBlock)completionHandler;

Now in this specific case, there is no use in calling this method without a completion handler, as it triggers a redundant call to a login web service (also, it does not change the state of anything - not client side nor server side). I would like to avoid these situations by actively enforcing the requirement of passing me a completion block in order to make this web service call. I sort of think of this as a "@required" method in an Objective C protocol. So my questions are:

  1. Is requiring a completion block in order to perform an action good practice in Objective C?
  2. (Edit: Answered) How do I enforce this requirement? Is there built-in language syntax that can help me out here?

Thanks

¿Fue útil?

Solución

You can use the function attribute nonnull(params), where params is 1 or more comma-separated parameter numbers, to indicate that a parameter should not be null (nonnull without parentheses means all pointer parameters should not be null). For your example:

- (void) loginWithUsername:(NSString *)username
               andPassword:(NSString *)password
            withCompletion:(LoginManagerCompletionBlock)completionHandler
                           __attribute__((nonnull(3)));

However, while this is a compile time check and produces a warning it will only do so if null is passed directly. If the argument value is an expression which evaluates to null, e.g. a variable with a null value, then this will not be caught.

If a parameter being null is an error you can add a runtime check within the method itself using NSParameterAssert(parameter), where parameter is the name of one of the method's parameters, to check for this condition. This call is defined to print an error message and throw an exception if its argument evaluates to false, and null evaluates to false.

Otros consejos

This is exactly what NSParameterAssert is for. Use it to check that parameters aren't nil.

NSParameterAssert( completionParameter );

Though, in this specific case, it's probably best to log the completion handler being nil and return. There is no point doing any additional work. You probably want the assertion during development to make it obvious that you have an issue that needs to be resolved.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top