2

I'm brand new to Objective C, and this may be somewhat of a lame question but:

I'm trying to make an iOS game, in which there is a class 'Monster' which generates a new instance of Monster every second or so, I want to be able to keep track of each Monster in order to use/manipulate it somehow.

Currently I'm trying to issue each Monster an unique ID,

e.g something like this:

//Incorrect Syntax ... 
Class Monster extends CCSprite

    public static global_id = 0;
    public instance_id;

    init() {
           instance_id = global_id;
           global_id ++;
    }

How would I manage this in the header/implementation file for class Monster? It seems like "static" 'doesn't exist' in Objective-C.

1
  • what do you mean? static variable (and global variable) does exist in Objective-C (in fact, inherited from C) Commented Jul 14, 2014 at 22:36

2 Answers 2

3

You'd normally work around the problem by:

  • sticking to the one-class-per-source-file rule;
  • putting a suitable global variable within that file;
  • marking the global variable as static, which in C terms means "not accessible from outside of this compilation unit" (and one source file is one compilation unit if you don't go out of your way with the preprocessor).

So, interface:

@interface AEMonster: CCSprite
@property (nonatomic, readonly) int instanceID;
@end

Implementation:

static int globalID = 0;

@implementation AEMonster

- (instancetype)init
{
    self = [super init];

    if(self)
    {
        _instanceID = globalID;
        globalID ++;
    }

    return self;
}

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

Comments

2

Your example didn't look like pure Objective-C. Objective-C does support static definitions. What you're describing is a classic Factory/Singleton pattern, and it would look like this:

MyClass.h:

@interface MyClass : NSObject

+ (id)getInstance;

@end

MyClass.m:

#import "MyClass.h"

+ (id) getInstance
{
    static MyClass *myClass = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        myClass = [[self alloc] init];
    });

    return myClass;
}

This is the singleton part of the pattern, where you call MyClass *c = [MyClass getInstance]; to get a reference to the instance. Only one instance will ever exist, and this is great for things where you want something semi-global but with a better pattern (things like network services are great examples).

A Factory pattern is just a step beyond this. You build MyClass exactly the same way, but instead of a getInstance() method you would have a createMonster() method. That would take any parameters required to create the type of Monster you wanted (this pattern is especially useful when you're going to have a Monster base class and then sub-classes of specific Monster types).

That's where you would generate your unique ID. Just add another static member variable inside the factory function and you can increment it each time it's called. That's a really naive unique ID generator, though - you probably want to make sure what you do is thread-safe, too. (That's another story.)

5 Comments

From my understanding, it seems like the + indicates static. What does it mean when I call a static method multiple times? Am I generating a new static global_id each time I call this constructor?
It depends what you put in your constructor. + does basically mean "static" in Objective C. But it's making the method static, so no matter how many copies of this class you have, whatever is inside that method only exists one time. Now expand that to your case: if you declare a static global ID inside that function, it now only exists once, and you can (watch thread safety!) increment it on each call to have a unique, incrementing ID.
Note: class method is different to static method (in other language). static methods are resolved at compile-time (so called static) but class methods are resolved at run-time so it can be overridden.
Also, from the C angle: a local variable declared static is one that has a lifetime equal to the application rather than to the call stack; it's basically a global that's visible only locally. So it's even more restricted than a class variable in other languages.
Both of these are excellent points, and 100% true. But for what it's worth, I think the original question was more about static locals inside functions, and in that case Objective-C is almost 1:1 identical to standard C: a primitive data type declared static inside a method works the same way in both. Don't forget your thread safety!!!

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.