Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a function in objective-c, that I can use over any object in my iPhone app?

I want to create a 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?

like image 499
Thanks Avatar asked Apr 25 '09 11:04

Thanks


2 Answers

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.

like image 50
Jason Coco Avatar answered Nov 05 '22 14:11

Jason Coco


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.

like image 1
Rog Avatar answered Nov 05 '22 15:11

Rog