8

I am developing an application on iOS. I see there is a macro called NSAssert1. What is it for? What are the differences in usage between NSLog and NSAssert1?

Please guide me or suggest a tutorial where I can read about it.

Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
Getsy
  • 4,887
  • 16
  • 78
  • 139

2 Answers2

29

NSAssert variants take a condition and a message. If the condition isn't met/true, then the assertion fails and NSAssert raises an exception with the message provided. For example, NSAssert((a == b), @"Error message"); will raise an exception when a is not equal to b. NSAssert1 is a variant that takes an additional argument and inserts it into the format string provided, like so: NSAssert1((a == b), @"Error message: %@", someErrorString);

NSLog will just write something to the console.

Documentation for all of those macros is on Apple's developer site.

Aron
  • 3,419
  • 3
  • 30
  • 42
  • 1
    But why couldn't they just have the one function that handled the arguments like `[NSString stringWithFormat:....]`, why have 5 extra variants of `NSAssert`? I know you're not Apple, but just wondering if anyone knows. – DonnaLea May 10 '12 at 07:02
  • 2
    Ahhhh: "In order to provide the method and line number information, the NSAssert() routine must be implemented as a macro, and therefore to handle different numbers of arguments to the format string, there are 5 assertion macros for methods: NSAssert(condition, description), NSAssert1(condition, format, arg1), NSAssert2(condition, format, arg1, arg2), …, NSAssert5(…)." - http://mike.rssmemo.com/?p=40 – DonnaLea May 10 '12 at 07:04
  • nil has provided example of A and B. But, the same could have achieved with `If` condition too. What is the difference between If and `NSAssert` ? – NSPratik May 21 '15 at 13:06
  • Also important to note that NSAssert will generally *not* raise an exception in release builds; though this depends on the release configuration. – Aron Jun 14 '18 at 13:29
5

NSAssert, NSParameterAssert, NSAssert1, and friends are assertion macros. Assertions are condition checks that scream when something is not right:

- (void) doSomethingWithPointer: (Foo*) foo
{
    NSAssert(foo != NULL, @"The Foo pointer must not be NULL!");
    foo->something;
}

See questions tagged “assertions” here on Stack Overflow for more information.

Community
  • 1
  • 1
zoul
  • 102,279
  • 44
  • 260
  • 354