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