How do I declare class-level properties in Objective-C?

Objective CCocoaOop

Objective C Problem Overview


Maybe this is obvious, but I don't know how to declare class properties in Objective-C.

I need to cache per-class a dictionary and wonder how put it in the class.

Objective C Solutions


Solution 1 - Objective C

properties have a specific meaning in Objective-C, but I think you mean something that's equivalent to a static variable? E.g. only one instance for all types of Foo?

To declare class functions in Objective-C you use the + prefix instead of - so your implementation would look something like:

// Foo.h
@interface Foo {
}

+ (NSDictionary *)dictionary;

// Foo.m
+ (NSDictionary *)dictionary {
  static NSDictionary *fooDict = nil;
  if (fooDict == nil) {
    // create dict
  }
  return fooDict;
}

Solution 2 - Objective C

I'm using this solution:

@interface Model
+ (int) value;
+ (void) setValue:(int)val;
@end

@implementation Model
static int value;
+ (int) value
{ @synchronized(self) { return value; } }
+ (void) setValue:(int)val
{ @synchronized(self) { value = val; } }
@end

And i found it extremely useful as a replacement of Singleton pattern.

To use it, simply access your data with dot notation:

Model.value = 1;
NSLog(@"%d = value", Model.value);

Solution 3 - Objective C

As seen on WWDC 2016/XCode 8 (what's new in LLVM session @5:05). Class properties can be declared as follows

@interface MyType : NSObject
@property (class) NSString *someString;
@end

NSLog(@"format string %@", MyType.someString);

Note that class properties are never synthesized

@implementation
static NSString * _someString;
+ (NSString *)someString { return _someString; }
+ (void)setSomeString:(NSString *)newString { _someString = newString; }
@end

Solution 4 - Objective C

If you're looking for the class-level equivalent of @property, then the answer is "there's no such thing". But remember, @property is only syntactic sugar, anyway; it just creates appropriately-named object methods.

You want to create class methods that access static variables which, as others have said, have only a slightly different syntax.

Solution 5 - Objective C

Here's a thread safe way of doing it:

// Foo.h
@interface Foo {
}

+(NSDictionary*) dictionary;

// Foo.m
+(NSDictionary*) dictionary
{
  static NSDictionary* fooDict = nil;

  static dispatch_once_t oncePredicate;
    
  dispatch_once(&oncePredicate, ^{
        // create dict
    });

  return fooDict;
}

These edits ensure that fooDict is only created once.

From Apple documentation: "dispatch_once - Executes a block object once and only once for the lifetime of an application."

Solution 6 - Objective C

As of Xcode 8 Objective-C now supports class properties:

@interface MyClass : NSObject
@property (class, nonatomic, assign, readonly) NSUUID* identifier;
@end

Since class properties are never synthesised you need to write your own implementation.

@implementation MyClass
static NSUUID*_identifier = nil;

+ (NSUUID *)identifier {
  if (_identifier == nil) {
    _identifier = [[NSUUID alloc] init];
  }
  return _identifier;
}
@end

You access the class properties using normal dot syntax on the class name:

MyClass.identifier;

Solution 7 - Objective C

Properties have values only in objects, not classes.

If you need to store something for all objects of a class, you have to use a global variable. You can hide it by declaring it static in the implementation file.

You may also consider using specific relations between your objects: you attribute a role of master to a specific object of your class and link others objects to this master. The master will hold the dictionary as a simple property. I think of a tree like the one used for the view hierarchy in Cocoa applications.

Another option is to create an object of a dedicated class that is composed of both your 'class' dictionary and a set of all the objects related to this dictionary. This is something like NSAutoreleasePool in Cocoa.

Solution 8 - Objective C

Starting from Xcode 8, you can use the class property attribute as answered by Berbie.

However, in the implementation, you need to define both class getter and setter for the class property using a static variable in lieu of an iVar.

Sample.h

@interface Sample: NSObject
@property (class, retain) Sample *sharedSample;
@end

Sample.m

@implementation Sample
static Sample *_sharedSample;
+ ( Sample *)sharedSample {
   if (_sharedSample==nil) {
      [Sample setSharedSample:_sharedSample];
   }
   return _sharedSample;
}

+ (void)setSharedSample:(Sample *)sample {
   _sharedSample = [[Sample alloc]init];
}
@end

Solution 9 - Objective C

If you have many class level properties then a singleton pattern might be in order. Something like this:

// Foo.h
@interface Foo
        
+ (Foo *)singleton;
        
@property 1 ...
@property 2 ...
@property 3 ...
        
@end

And

// Foo.m

#import "Foo.h"

@implementation Foo

static Foo *_singleton = nil;

+ (Foo *)singleton {
    if (_singleton == nil) _singleton = [[Foo alloc] init];

    return _singleton;
}

@synthesize property1;
@synthesize property2;
@synthesise property3;

@end

Now access your class-level properties like this:

[Foo singleton].property1 = value;
value = [Foo singleton].property2;

Solution 10 - Objective C

[Try this solution it's simple] You can create a static variable in a Swift class then call it from any Objective-C class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmamcxView Question on Stackoverflow
Solution 1 - Objective CAndrew GrantView Answer on Stackoverflow
Solution 2 - Objective CspookiView Answer on Stackoverflow
Solution 3 - Objective CAlex NolascoView Answer on Stackoverflow
Solution 4 - Objective CJim PulsView Answer on Stackoverflow
Solution 5 - Objective CQuentinView Answer on Stackoverflow
Solution 6 - Objective CberbieView Answer on Stackoverflow
Solution 7 - Objective CmouvicielView Answer on Stackoverflow
Solution 8 - Objective CJean-Marie D.View Answer on Stackoverflow
Solution 9 - Objective CPedro BorgesView Answer on Stackoverflow
Solution 10 - Objective CjawadView Answer on Stackoverflow