Search code examples
iosobjective-cclass-methodclass-members

When I change from instance to class method, why is 'self' no longer allowed?


I'm afraid this is a stupid question, but I honestly don't understand.

I have a class, RemoteConfiguration and currently it's functionality is all instance methods. This being so, I have to use it like:

RemoteConfiguration* configs = [[RemoteConfiguration alloc] init];
[configs updateSettings];
[configs release];

This is annoying because there is no need to create an object just to use one method which could be a class method and called like:

[RemoteConfiguration updateSettings];

But when I change my methods from - to + Xcode complains about every object I access with self, suggesting that I use -> instead. (Which also causes a warning) I don't get this. Regardless of the methods, the object will still have its member variables. So why is -> necessary? And how can I use member variables in class methods?


Solution

  • Within a class method, the keyword self doesn't refer to an instance of that class type, but rather the actual class instance, as in the result of [RemoteConfiguration class].

    Class instances like this do not have instance variables (at least not the ones you're declaring, but rather the Class instance variables, most notably the isa instance variable).

    If you wish to have a single static instance of RemoteConfiguration you can declare the instance variables as static variables within the .m file, or use something like the singleton pattern to keep an instance handy.