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
|
1 |
NSLog(@"Simple log"); |
Strings
|
1 2 |
NSString *myString = @"I am a string";
NSLog(@"Value of myString is %@", myString); |
Boolean
|
1 2 3 4 |
BOOL myBool = YES;
NSLog(@"Value of myBool is %d", myBool);
//or
NSLog(@"Value of myBool is %@\n", (myBool ? @"YES" : @"NO")); |
Dates
|
1 2 |
NSDate *myDate = [NSDate date];
NSLog(@"Value of myDate is %@", myDate); |
Floats
|
1 2 |
double myDouble = 1.5;
NSLog(@"Value of myDouble is %f", myDouble); |
Integer or Long
|
1 2 |
int myInt = 90;
NSLog(@"Value of myInt is %i", myInt); |
Arrays & Dictionaries
|
1 2 |
NSArray * myArray = [NSArray arrayWithObjects:@"Value 1", @"Value 2", @"Value 3", nil];
NSLog(@"Value of myArray is %@", myArray); |
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:
|
1 |
NSLog(@"Dump of MyViewController %@", self); |
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:
|
1 2 3 |
- (NSString *)description {
return [NSString stringWithFormat:@"\nProperty 1: %@ \nProperty 2: %@", self.myProp, self.anotherProp];
} |
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
