16

(I'm a cocoa beginner and ) I'm wondering why we should do:

NSLog(@"this is the variable value: %d",variable);

and not something like this:

[NSLog outputThis:@"this is the variable value: %d" param:variable];
tahir
  • 1,016
  • 1
  • 11
  • 21
  • 1
    Because second statement calls `outputThis:param:` method on `NSLog` object. `NSLog` is just a function in Cocoa framework. – Eimantas Jun 25 '12 at 13:47
  • yes but it could have been a class method for a class NSLog, like [NSString stringWithString:@"this is a string"]; ? – tahir Jun 25 '12 at 13:50
  • NSLog does not "sound" like class. NSLogger would've been better choice for a class name. Now it's just an action. – Eimantas Jun 25 '12 at 13:57
  • 4
    because the second one looks shit and we should feel blessed for anything that looks more like C ;) – Dominic Dec 04 '13 at 22:29

3 Answers3

19

I agree this is pretty confusing when you're starting out. The main reason is that the NSLog method, like many others in Core Foundation, is a C-based API, rather than an Objective-C API. C-style functions look like this myFunction(myParameter1, myParameter2).

All the GUI stuff you're probably used to [UIView presentModalViewController:] etc is based around an Objective-C API, with the square brackets that you've seen for functions (called selectors in Obj-C) . The Objective-C language sits on top of C, so you will find both styles in most apps.

Ben Clayton
  • 80,996
  • 26
  • 120
  • 129
7

NSLog may seem like a class, but it isn't.

NSLog is a FoundationKit function for printing debug statements to the console. It is defined in NSObjCRuntime.h:

void NSLog(NSString format, ...);

There is a good amount of information here: http://cocoadev.com/wiki/NSLog

EDIT: As @fyngyrz pointed out, the page is dead. So here is a wayback-machine version of the page from 2012

Alladinian
  • 34,483
  • 6
  • 89
  • 91
6

As I understand it, NSLog isn't an Objective C function but a C function built into the foundation of Cocoa. Therefore it conforms to basic C functions with variadic arguments.

John Topley
  • 113,588
  • 46
  • 195
  • 237
Ryan Poolos
  • 18,421
  • 4
  • 65
  • 98