Hi guys,
I need to create a global function that will be accessible to all classes in my
project.
What is the best or at least practical way to do it?
Thanks!!
A fast, easy to use, free, and community supported 2D game engine
Hi guys,
I need to create a global function that will be accessible to all classes in my
project.
What is the best or at least practical way to do it?
Thanks!!
Hi,
I am by no means an expert, but here is what I do.
I use a singleton class.
http://en.wikipedia.org/wiki/Singleton_pattern
It is a class much like the cocos director.
http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html
There is a nice link about them, it can be used for functions. Just skip down to the singleton section. Singletons are great for global variables too.
You can also make static methods, it +(void)myFunction in a class.
So you can call them like [MyClass myFunction:value].
This has no way to store data, so I prefer singletons.
Another way you could do it with functions, is add it in a C header. For example:
#define RADIANS_TO_DEGREES(__ANGLE__) ((__ANGLE__) / M_PI * 180);
will convert radians to degrees.
Hope that helps.
Thanks I finally got it working using singleton!
glad I can help.
If you want a "global" function, you probably don't even need a singleton. Just define it as a class function rather than an instance function, ie:
+ (void) doSomething: (int) aParameter param2: (NSString *) anotherParameter;
This function can then be called using:
[YourClass doSomething: ... param2: ...];
and you don't even need to allocate an instance of YourClass. This will save you a bit of memory overhead and simplify your coding.
EDIT: Also, if you can write your function in C rather than Objective C, you can just put it directly in whatever header you'd like - your prefix header, for example - and call it directly as a C function. I frequently do this for simple mathematical functions, such as a log approximation I use for some of my calculations.
This approach sounds good to. I'll give it a try.
Thanks for all your help guys!
You must log in to post.