Global Objects

Apprentice
Posts: 14
Joined: 2008.08
Post: #1
How would one go about having an object accessible from any other object method?

eg: I have an object which manages textures, and want to be able to access it from the openGL view object. (or any other object).

How do I go about doing this, or is there a better way of doing it?

Thanks =)
Quote this message in a reply
Moderator
Posts: 3,577
Joined: 2003.06
Post: #2
You can use what is called a singleton.
Quote this message in a reply
Moderator
Posts: 1,560
Joined: 2003.10
Post: #3
Here's one approach.

TextureManager.h:
Code:
+ (TextureManager *) sharedInstance;

TextureManager.m:
Code:
static TextureManager * sharedInstance = nil;

+ (TextureManager *) sharedInstance {
  if (sharedInstance == nil) {
    sharedInstance = [[TextureManager alloc] init];
  }
  return sharedInstance;
}

In some cases it may be a better design to pass a TextureManager instance to your view rather than having the view reach out and get one. This allows greater flexibility, as a view doesn't always have to use the same TextureManager instance. However, if you know you truly will only ever need one, the singleton approach is simpler and therefore better.

Here's some interesting reading about singletons: http://googletesting.blogspot.com/2008/0...oject.html
Quote this message in a reply
Apprentice
Posts: 14
Joined: 2008.08
Post: #4
Thank you very much for that, it works!

Thanks for the links to, looks interesting.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Alternative to a global VLA ferum 6 4,346 Jul 24, 2006 06:47 PM
Last Post: OneSadCookie