Is there a way to synthesize setters / getters for class variables in Objective-C?

I found myself declaring a bunch of class variables and it is very tedious to write simple get / set methods for each variable. So the question is how to synthesize setters / getters for class variables in objective-c?

+2


source to share


4 answers


Typically, when you group a set of related variables that need to be accessed globally, you create a so-called Singleton:

What should an Objective-C singleton look like?

This means that you have one class-level method that returns a generic instance to you - so you have a call like this:

[MyClass sharedInstance].myProperty

      



Since the values ​​you store are instance variables of the true class, you can use normal properties, but all classes will work with the same shared data.

Note that some people don't like the use of singletons, you can read some caveats about practice:

Singleton: how to use it

But since you're already starting out with one integral singleton in iPhone development (an application delegate that anyone can access at any time), it doesn't hurt to make this technology easier to use if you're careful. Note that instead of creating a Singleton class, one alternative is to delegate the application to create one instance of the storage variables class and access it via the delegate ...

+4


source


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

@property (retain) NSString* caption;

      

then it happens directly inside the implementation:



@synthesize caption;

      

Check out this tutorial for more details: http://www.cocoadevcentral.com/d/learn_objectivec/

+1


source


Can't you just create a macro editor or something?

0


source


The property doesn't need to be referenced by ivar. You can have a dynamic property if you really want to return a static variable.

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

0


source







All Articles