Logging to Console

Day 6

Just a simple one for today, but an important one nonetheless: logging to console.

Most of my experience logging to the console comes from JavaScript using console.log(). Objective-C’s equivalent is similar but – I feel like I’m saying this a lot lately – the syntax is a little strange to me. Anyway, logging to console is done using NSLog, here are some examples:

Simple

Strings

Boolean

Dates

Floats

Integer or Long

Arrays & Dictionaries

NSObjects

What if you want to print your ViewController, or some other object you’re working with, along with all its properties? You can do so using the same method as Arrays and Dictionaries, for example:

However, the output is going to be pretty underwhelming. Instead of a list of all properties, you’ll get something like this:

<MyViewController: 0x6867e90>

Not very useful :/

It turns out, all objects in Objective-C inherit from NSObject, and NSObject contains a method called description which you can exploit. Place this somewhere inside the implementation file:

Doing this overrides the description method and allows you to control exactly what gets output to the console. Now whenever you NSLog your object, its description class will be run. Handy! :D