codescracker


objective c

Objective-C Log Handling



« Previous Tutorial Next Tutorial »


NSLog method in Objective-C

To print logs in Objective-C, we use the NSLog method of Objective-C, which we have used right from the Hello, World example. Here is an example program, prints the words "Hello, World" in Objective-C:

/* Objective-C Log Handling - Example Program */
		
#import <Foundation/Foundation.h>
int main()
{
	NSLog(@"Hello, World\n");
	return 0;
}

When we compile and run the above program, we will get the following result:

2014-10-03 13:18:37.932 demo[16669] Hello, World

How to disable logs in live apps in Objective-C ?

As the NSLogs that we use in our applications, it will be printed in logs of devices and it is not good to print the logs in live build. Therefore, we use a type definition for printing the logs and we can use them like this:

/* Objective-C Log Handling - Example Program */
		
#import <Foundation/Foundation.h>

#if DEBUG == 0
#define DebugLog(...)
#elif DEBUG == 1
#define DebugLog(...) NSLog(__VA_ARGS__)
#endif

int main()
{
	DebugLog(@"Debug log, our custom addition gets printed during the debug only");
	NSLog(@"NSLog gets printed always");     
	return 0;
}

Now, when we compile and run the above program in debug mode, we will get the following result:

2014-10-03 13:18:37.932 demo[618] Debug log, our custom addition gets printed during the debug only
2014-10-03 13:18:37.932 demo[618] NSLog gets printed always

Now, when we compile and run the above program in release mode, we will get the following result:

2014-10-03 13:18:37.932 demo[3158] NSLog gets printed always

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test