0

I would like to use class variables outside of the class.

By 'outside', I mean the main function where I instantiate the class.

@interface Class: NSObject
static int var_class;   // Class variable
{
    int var_object; // Object variable
}
@end

@implementation Class
@end

In order to access var_object, the object variable, we use:

int main(void)
{
    Class *object = [Class new];

    // Access to the variable
    object->var_object;
    (*object).var_object;

    return 0;
}

I thought I could access var_class, the class variable, in the same way.

But none of them worked. (Unable to compile)

Class.var_class;
// -> Generates error: could not find setter/getter for 'count' in class 'TheClass'

Class->var_class;
// -> Generates error: error: expected '.' before '->' token

How can I get/set the class variable's value?

Declaring a function is the way to access class variables, but I want it simpler.

@interface Class: NSObject
static int var_class;   // Class variable
+(int) get;
+(void) set: (int) val;
@end

@implementation Class
+(int) get
{
    return var_class;
}
+(int) set: (int) val
{
    var_class = val;
}
@end
Gimgane
  • 3
  • 2

1 Answers1

0

There is no static class variables in Objective-C, thus you can't expect something like Class.var_class. This is why your last proposition is a correct one, and commonly adopted. See, Does Objective-C support class variables?.

----EDIT----

Some new constructions were added to Objective-C, see Objective-C Class Properties. Thus syntax is admitted, while there is no automatic synthesis.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
  • 1
    Actually `Class.var_class` syntax is possible with `@property(class, ...) ` and technically even without it, but not to access the variable itself only the class property. – Kamil.S Jan 06 '20 at 07:18
  • @Kamil.S Excellent, I was not aware that Objective-C evolved even after Swift tried to replace it! Thanks. – Jean-Baptiste Yunès Jan 06 '20 at 07:26
  • So I have to create a function or use a property instead. Thank you both! – Gimgane Jan 06 '20 at 07:44