Question

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?

Was it helpful?

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.

OTHER TIPS

Without seeing the code it sounds like you are referencing self from within the method that you want to be a class method.

You cannot reference self because you are performing an action on the class, not an instance of the class. Hence self does not refer to what expect.

You'll have to modify the method if you truly seek it to be a class method. Keep in mind, you'll only have local variables and static variables to work with. If you have any properties or instance variables you wont have access to those either.

“self” points to the instance. A class method does not have any instance associated with it.

Basically, if you call a class method, “the object” that “will still have its member variables” is not “seen” by the method, because it’s a method on the class as a whole, not on specific individual objects.

You can probably pass one to it – but then, why use a class method in the first place? (In short: don’t.)

There’s also the possibility to use class variables instead of instance variables, in theory… it all depends.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top