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

mamcx picture mamcx · Mar 30, 2009 · Viewed 144.1k times · Source

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.

Answer

Andrew Grant picture Andrew Grant · Mar 30, 2009

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;
}