Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling class methods via self

Tags:

objective-c

I have some class methods in a class with a pretty long name (TimingConfigController to be exact), and I call those methods quite often from within the class (example: [TimingConfigController intervalStringAt:i]), but the long class name bothers me because the statements get very long and less readable with all that inlined.

I was reading up to see if I could find a shorthand alternative, and I came upon this article on developer.apple.com: Defining a Class

It says, among other things, that

id newInstance = [[self alloc] init];

is an excellent way to make an object of the same class that self is. As far as I can tell, that statement calls a class method using the self pointer instead of the class name, so I tried that in my app, and although it might work, it gives a compiler warning. I really don't want to have warnings.

So, my questions are, is using self to call a class method possible and/or a good idea? Are there any better alternatives? Would it be terrible of me to do a #define Self TimingConfigController at the start of the .m file? Or should I just take my meds and live with the annoyances?

like image 637
user362178 Avatar asked Jan 21 '23 21:01

user362178


1 Answers

self only represents a class inside a class method. Because the target of a class method is a class, self represents the class.

For example, inside an + (void)initialize method, it is common to see:

+ (void)initialize {
    if (self == [MyClass class]) { // <- self is the current class
        // ...
    }
}

If you really want to shorten the class name without renaming it, the simplest solution is to use a #define statement:

#define TCC TimingConfigController

// The two lines are equivalent
id result1 = [TimingConfigController theClassMethod]; 
id result1 = [TCC theClassMethod];
like image 114
Laurent Etiemble Avatar answered Jan 31 '23 02:01

Laurent Etiemble