I know it supports automatic variables, but what about class variables?
Unlike other C-based languages, Objective-C uses “@” for declarative statements. You always declare a new class with @interface, followed by your custom class name, followed by a colon and ended with the name of your class' superclass. Finally, we'll see @end on line 13.
Objective-C Classes Are also Objects In Objective-C, a class is itself an object with an opaque type called Class . Classes can't have properties defined using the declaration syntax shown earlier for instances, but they can receive messages.
Objective-C is more like C/C++ than Java. Java is relatively unique in that it doesn't have separate declaration and implementation files but puts everything in one file. In Objective-C you declare the instance fields in the @interface section of your . h file.
It's Shorthand writing. In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals.
The language does not support class variables. You implement class-specific state with global static
variables in the compilation units of the implementation.
In the header (.h file):
@interface MyClass : NSObject
+(int)val;
@end
In the implementation (.m file):
static int val = 123;
@implementation MyClass
+(int)val {return val;}
@end
Usage:
if ([MyClass val] > 100) ...
ObjC class variables are plain old static variables.
Foo.m
:
static int foo = 0;
Alternatively, you can use a C++ anonymous namespace if you use ObjC++:
Foo.mm
:
namespace {
int foo = 0;
}
But there is another pattern if you want to benefit from the advantages of properties:
Foo.h
:
@interface FooShared
@property ( atomic, readwrite, strong ) Foo* foo;
@end
@interface Foo
+ (FooShared*) shared;
@end
Foo.m
:
@implementation FooShared
@end
static fooShared* = nil;
@implementation Foo
+ (FooShared*) shared
{
if ( fooShared == nil ) fooShared = [FooShared new];
return fooShared;
}
@end
somewhere.m
:
Foo* foo …;
foo.shared.foo = …;
It may look a bit overkill, but it's a interesting solution. You use the same constructs and language features for both instance properties and "class" properties. Atomicity on demand, accessors when needed, debugging, breakpoints... Inheritance even.
Creative minds can find other ways to do all this I suppose. :) But you're pretty much covered with these options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With