0

I'm trying to extend NSLog that can print any type of object. Means, my custom class gets the value that need to be printed from the user and checks its class type and then it will print as desired format.

Consider my extended class name is, MyLog (So it contains MyLog.h and MyLog.m)

MyLog.h:

void MyLog (id objectValue);

MyLog.m:

#import "MyLog.h"

void MyLog (id objectValue)
{
    if ([objectValue isKindOfClass:[NSString class]])
    {
        NSLog(@"%@",objectValue); //Same for NSArray, NSDictionary, NSMutableArray, NSMutableDictionary
    }

    else if ([objectValue isKindOfClass:[NSData class]])
    {
        NSLog(@"%@",[[NSString alloc]initWithData:objectValue encoding:NSUTF8StringEncoding]);
    }

    ....
    ....
}

So, if I include this class (MyLog.h) in prefix file, I can call the below method from any class to simply print the given object.

MyLog(valueOfObject);

Problems:

  • The CGRect, CGpoint, CGSize related things (which are not an object) can not be passed as id to MyLog() function.

  • I tried to print the object name along with its value for more readability. Refer this post.

For example,

NSString *myString = @"Welcome";

MyLog(myString);

This will print myString: Welcome instead of just printing Welcome.

I can achieve this my defining a preprocessor like

#define MYLOG(x) NSLog( @"%s:%@",#x, x)

So, I tried to customize it in the following way

#define MYLOG(x) NSLog(@"%s:%@",#x, MyLog(x))

But it throws "Argument type 'void' is incomplete" error.

Questions:

  • How can I pass non objects as id to a function?
  • How can I call a function within a preprocessor macro?

Help needed!! Just Confused!!

Community
  • 1
  • 1
Confused
  • 3,846
  • 7
  • 45
  • 72

1 Answers1

0

If you implement -(NSString*)description you can print any object in NSLog with NSLog(@"%@", myObject).

So just add -(NSString*)description in the classes of objects that you want to print out, and in them just return the NSString value that you think is relevant for that object.

Stefan Salatic
  • 4,513
  • 3
  • 22
  • 30
  • Is this answer for my question 1? – Confused Apr 28 '15 at 09:39
  • This isn't directly an answer to your question, but a suggestion on how to do it easier. There is no need to create your own NSLog. If you want, I can show you how to write code for your exact function, but I really advise against it since you already have a perfect solution built in. – Stefan Salatic Apr 28 '15 at 09:42
  • When you pass an object into NSLog, the `description` method is called. So all you need to do is make sure you implement it in your class. – Stefan Salatic Apr 28 '15 at 09:43