How do I declare 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? Eg 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;
}

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

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.

链接地址: http://www.djcxy.com/p/78788.html

上一篇: 静态构造函数和单例类

下一篇: 我如何申报课程