views:

1892

answers:

3

I want to create an function which I pass an object. Then, this function should print out some information for me.

like:

analyzeThis(anyObject);

I know about methods, but not how to make a function. As I understand, a function works global in all methods and classes, right?

+8  A: 

You would do it the same way as any other function that you would write in C. So, if you have your function defined in a source file named myLibraryFunctions.m, anyone who wanted to use that function would include the header file where you define it (probably myLibraryFunctions.h, and then just make sure that they link with the object file (most of this will be done for you in Xcode if you simply create a file to house your "global" functions and include the header file for them in any source file that you access it from. Then just define it:

void analyzeThis(id anyObject);

void analyzeThis(id anyObject) {
    NSLog(@"Object %p: %zu, %@", anyObject, malloc_size(anyObject), anyObject);
}

But in reality, you would write whatever you wanted in your function. These functions don't have to be a part of any class definitions or anything like that. In this case, they're exactly the same as they would be in C.

Jason Coco
Thanks! Where's the hidden option in XCode to set up that global function file, so that XCode would make all the header imports for me? That would be great!
Thanks
Add the header import to your precompiled header. It will be the one with your project name and then _pch at the end. It is usually under the "Other Sources" group in an Xcode project.
Jason Coco
+1  A: 

Are you trying to reimplement NSObject's description method? If you send an NSObject message it will return a string containing information about itself. You can override -(NSString*)description and add more information to this string.

If you do this, you'll find that magic happens - for example when you print an array object in the debugger it will iterate all the members of the array and print their descriptions.

Roger Nolan
Nice hint, thanks. Actually I wanted to try out something regarding memory management. A function that will check prior to an release message if the object still exists. May be useful. I'm not sure yet.
Thanks
If you are creating that method for debugging, you really should look at using NSZombie.If you are using it as a guard at runtime, it could cause other issues...
Kendall Helmstetter Gelner
This seems completely distinct from NSZombie.
Roger Nolan
+1  A: 

Two ways exist for doing this:

  • write a global function, just as you would do in C
  • create a category of NSObject in which you implement a method which then will be available to all classes that have NSObject as ancestor.
mouviciel