0

I just want to make sure I'm using class methods correctly.

By way of example, let's say I'm creating a game that involves a single map and individual tiles on that map (for instance, 16 x 16 tiles).

Each tile can consist of either a building, tree, road, etc - and this can change throughout the game.

Would I be correct in setting up a Map class with a class method to initialise the map, simply because there will only be one map and I would have no need to instantiate more than one?

Would I also be correct in setting up a Tile class with instance methods to initialise the tiles, because there would be 256 tiles each with their own properties?

Struggling to get my head around it all, any advice would be greatly appreciated.

2 Answers 2

1

There are multiple patterns for dealing with this, but basically it boils down to the Map class being a singleton. Some prefer to enforce the singleton-ness of the class by disallowing the creation of multiple instances (for example, by hiding the constructor, or making the constructor throw an exception, etc). In other cases it just suffices to document the Map class as being a singleton and use it as such.

A simple way of dealing with singletons in Objective-C is to create a class method for instantiating it, i.e.:

static Map* defaultMap = nil;
+ (Map*) defaultMap {
    if(!defaultMap) defaultMap = [[Map alloc] init];
    return defaultMap;
}

Using class methods for the map is probably not such a good idea, just like global variables is something that should usually be reduced to a minimum (though the example above is really a global variable, it will be a lot easier to refactor your code once you have a need for multiple maps).

Sign up to request clarification or add additional context in comments.

Comments

0

Map class can be implemented as singleton pattern. Or any other way that limits it to only 1 shared instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.