views:

565

answers:

4

I find myself declaring bunch of class variables and it is really tiring to write simple get/set methods for each variable. So, the question is how to synthesize setters/getter for class variables in objective-c?

A: 

Can you not just en editor macro or something?

Preet Sangha
+1  A: 

something like this goes in your header, after the interface:

@property (retain) NSString* caption;

then this goes immediatley inside the implementation:

@synthesize caption;

Check out this tutorial for more details: http://www.cocoadevcentral.com/d/learn%5Fobjectivec/

macinjosh
You should also note that this assumes an ivar named caption with NSString * as the type
rpetrich
That's what instant variables, but what about other types (like static) ?
Denis M
@Dennis: No you can not use properties on classes, only on object instances. For class variables you must implement getter and setter class methods manually.
PeyloW
Does not solve the question asked (properties at the class level, i.e. "+")
Kendall Helmstetter Gelner
A: 

A property doesn't need to reference an ivar. You can have a dynamic property return a static variable if you really want.

Just use @dynamic and implement the getter and setter to reference static variables from your implementation file.

Maven
Except that you would need an instance to call the property, instead of only using the class name...
Kendall Helmstetter Gelner
+2  A: 

Usually when you are grouping a set of related variables that are meant to be accessed globally, you create what is called a Singleton:

http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like

This means you have one class level method that gives you back a shared instance - so you'd have a call like:

[MyClass sharedInstance].myProperty

Since the values are you are storing are true class instance variables, you can use normal properties, but all classes will be working with the same shared data.

Note that some people dislike the use of singletons, you may want to read some caveats about the practice:

http://stackoverflow.com/questions/86582/singleton-how-should-it-be-used

But since you already start with one inherent singleton in iPhone development (the application delegate, which anyone can access at any time) making light use of the technique does not hurt if you are careful. Note that instead of creating a Singleton class, one alternative is to have the application delegate create a single instance of a variable storage class, and have everyone access that through the delegate...

Kendall Helmstetter Gelner
I guess I'll have to stick to this technique...
Denis M