tags:

views:

305

answers:

2

what is NSParameterAssert?can anyone explain with example?

+5  A: 

It is a simple way to test that a methods parameter is not nil or not 0. So basically, you use it to create a precondition, stating that some parameter must be set. If it is not set, the macro causes the application to abort and generates an error on that line. So:

- (void)someMethod:(id)someObjectThatMustNotBeNil
{
  // Make sure that someObjectThatMustNotBeNil is really not nil
  NSParameterAssert( someObjectThatMustNotBeNil );
  // Okay, now do things
}

Pre-conditions are a simple way to ensure that methods/API are being called correctly by the programmer. The idea is that if a programmer violates the precondition, the application terminates early--hopefully during debugging and basic testing.

NSParameterAssert can be used to test that any expression evaluates to true, however, so you can use it like this as well:

NSParameterAssert( index >= 0 ); // ensure no negative index is supplied
Jason Coco
its like if().....thx
Mikhail Naimy
Make sure to catch exceptions in your code, otherwise if the Assert is true, it'll crash your app.
lucius
@senthilmuthu It's not exactly like an if statement. They're similar in that they can evaluate an expression, but an if statement is used for program flow control, whereas NSParameterAssert, like Jason Coco's answer explains, will terminate the app if the evaluation results in true. If statements don't do that.
Jasarien
@lucius: Asserts are not to be used for checking conditions in a distributed application, they are there to catch errors during development. Causing something to crash on a bad condition (like an unconnected outlet to a Nib), rather than fail silently, lets you find problems early. Many people disable these at distribution time through macros or #ifdefs.
Brad Larson
@lucius - The goal is to cause the application to abort when preconditions are not met. This lets the programmer know immediately that s/he has done something wrong. To ensure that assertions in Cocoa are not evaluated you can define the NS_BLOCK_ASSERTIONS macro. This disables them, but the idea is to keep side effects or slow code from executing rather than guarding against crashing--by production, assertions should never trigger if used correctly.
Jason Coco
A: 

Use google, or try it out.

Now that you've done that, NSParameterAssert is just like NSAssert except you don't get the option to pass a string detailing what is being asserted - it just logs the expression you pass it.

codewarrior