Understanding NSLog syntax - objective-c

(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];

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.

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

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.

Related

Why does method_getNumberOfArguments return two more results than the selector would imply?

In the objective-C runtime, why does method_getNumberOfArguments return two more results than the selector would imply?
For example, why does #selector(initWithPrice:color:) return 4?
TL;DR
Alright. Just to set the record straight, yes, the first two arguments to any objective-c method are self and _cmd, always in that order.
A brief history of Objective-C
However, the more interesting subject is the why to this scenario. To do that, we must first look into the history of objc. Without further ado, let's get started.
Way back in 1983, Brad Cox, the 'God' of objective-c, wanted to create an object-oriented runtime-based language on top of C, for good performance and flexibility across platforms. As a result, the very first Objective-C 'compilers' were just simple preprocessors of Objective-C source converted to their C-runtime equivalents, and then compiled with the platform specific C compiler tool.
However, C was not designed for objects, and that was the most fundamental thing that Objective-C had to surmount. While C is a robust and flexible language, runtime support is one of it's critical downfalls.
During the very early design phase of Objective-C, it was decided that objects would be a purely heap-based pointer design, so that they could be passed between any function without weird copy semantics and such (this changed a bit with Obj-C++ and ARC, but that's too wide of a scope for this post), and that every method should be self aware (acually, as bbum points out, it was an optimization for using the same stack frame as the original function call), so that you could have, in theory, multiple method names mapped to the same selector, as follows:
// this is a completely valid objc 1.0 method declaration
void *nameOrAge(id self, SEL _cmd) {
if (_cmd == #selector(name)) {
return "Richard";
}
if (_cmd == #selector(age)) {
return (void *) (intptr_t) 16;
}
return NULL;
}
This function, then could be theoretically mapped to two selectors, name and age, and perform conditional code based on which one is invoked. In general Objective-C code, this is not too big of a deal, as it's quite difficult with ARC now to map functions to selectors, due to casting and such, but the language has evolved quite a bit from then.
Hopefully, that helps you to understand the why behind the two 'invisible' arguments to an Objective-C method, with the first one being the object that was invoked, and the second one being the method that was invoked on that object.
The first two arguments are the hidden arguments self and _cmd.

What is this objective-c function construct called?

I was looking through one of Apple's XCode tutorials and came across something that looked like this inside the implementation of a class method:
void (^foo)(void);
foo = ^(void) {
NSLog(#"Hello, World!");
};
foo();
Now obviously this is some kind of function declaration, implementation, and usage. However, I'd like to know more about it, what it is called, and what its limitations and advantages are. My searches online are turning up nothing relevant. Can anyone point me in the proper direction?
They're called blocks. You can think of a block as a chunk of code that you can pass around to other parts of your program. They were added by Apple to its C and Objective-C compilers relatively recently, but some newer APIs take blocks instead or in addition to selectors or function pointers.
Blocks and block variables.
Here's some reading:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html
http://pragmaticstudio.com/blog/2010/7/28/ios4-blocks-1
http://thirdcog.eu/pwcblocks/

C function vs. Objective-C method?

What is the difference between the two? If I'm writing a program, when would I need a this:
void aFunction() {
//do something
}
and when would I need this:
-(void)aMethod {
//do something else
}
Actually, an Objective-C method is just a C function with two arguments always present at the beginning.
This:
-(void)aMethod;
Is exactly equivalent to this:
void function(id self, SEL _cmd);
Objective-C's messaging is such that this:
[someObject aMethod];
Is exactly equivalent to this (almost -- there is a variadic argument ABI issue beyond the scope of this answer):
objc_msgSend(someObject, #selector(aMethod));
objc_msgSend() finds the appropriate implementation of the method (by looking it up on someObject) and then, through the magic of a tail call optimization, jumps to the implementation of the method which, for all intents and purposes, works exactly like a C function call that looks like this:
function(someObject, #selector(aMethod));
Quite literally, Objective-C was originally implemented as nothing but a C preprocessor. Anything you can do in Objective-C could be rewritten as straight C.
Doing so, however, would be a complete pain in the ass and not worth your time beyond the incredibly educational experience of doing so.
In general, you use Objective-C methods when talking to objects and function when working with straight C goop. Given that pretty much all of Mac OS X and iOS provide Objective-C APIs -- certainly entirely so for the UI level programming entry points -- then you use Obj-C most of the time.
Even when writing your own model level code that is relatively standalone, you'll typically use Objective-C simply because it provides a very natural glue between state/data & functionality, a fundamental tenant of object oriented programming.
In Objective-C each function operates on an object, like
[myObject myFunction]
A C method has the form:
return-type function-name(argument1, argument2, etc) {}
An Objective-C instance method has the form:
-(return-type)function-name:argument1 {}
or for a multi-argument function
-(return-type)function-name:argument1 function-name:argument2 {}
I always use Objective-C-style methods in Obj-C programming, even though you can still use C-type functions as well.
I suppose the equivalent in C to [myObject myMethod:arg] might be myObject.myMethod(arg)
The first is a freestanding function. The second is an instance method for an Objective-C class. So I guess you would need the second version if you're actually writing a class.

Translate Obj-C to C# (Monotouch)

Not knowing Obj-C I could use some help to traslate this one line of code:
[[TVOutManager sharedInstance] startTVOut];
into a C# version I can use in MonoTouch.
I've managed to get the XCode project compiled to a static library, now I'm trying to figure out how to turn it on... The orginal project is posted here: http://www.touchcentric.com/blog/
TIA,
Rick
[obj myMsg] is Objective-C syntax for sending the myMsg message to the obj instance. It is, at first blush, a lot like obj.myMsg() in C#. Objective-C uses message passing rather than function calls, however, so the two are actually very different semantically. You can often gloss over the differences, but if you are going to do any significant work on OS X or iOS, it's worth reading the Objective-C language guide carefully. I'm not a MonoTouch/MonoMac expert, but I believe that the answer to your specific question is:
TVOutManager.sharedInstance.startTVOut();
assuming sharedInstance is mapped as a static property of type TVOutManager, or
TVOutManager.sharedInstance().startTVOut();
if sharedInstance is mapped as a class method in Objective-C.

How to code a method, function or variable in Objective - C

I have just started to learn Objective - C. I have done one year of Java programming and one year of Actionscript. I need to find a website or blog which tells me how to do the basic things for example declare a variable or how to write a method and function. I cant seem to find this anywhere. If someone could give me some good links that would be great.
Thanks
Introduction to The Objective-C 2.0 Programming Language from Apple would probably be a good place to get started with the Objective-C language.
In general, declaring variables aren't too different within a method.
-(void)doSomething {
// Declaration of a variable.
int myVariable = 0;
}
The syntax for methods and functions can be a little bit different, and the language itself allows the use of C, as Objective-C is a superset of C.
One conceptual difference about classes and objects in Objective-C compared to Java is that the implementation and the declaration is separated into two different files. The "header" information which defines the interface is usually included in the .h file, while the implementation is included in the .m file.
The interface defines the methods, properties and such, while the implementation includes the actual code to use in the methods.
Also, strictly speaking, in Objective-C are not "methods" are not "called", but "messages" are "sent" to objects, and the objects react to them:
// The following is sending the "doSomething" message to "myObject".
// Strictly speaking, it's not a method call, but a messaging of an object.
[myObject doSomething];
Also, the Wikipedia article on Objective-C also gives a pretty good overview of the language as well.
I would highly recommend the book Programming in Objective-C 2.0 by Stephen Kochan.
I used the older version when I was learning Objective-C and still reference it on occasion. It is an excellent introduction to the basics of the language.