开发者

share a property among different instance of the same class

Is it possible to share one parameter of a class among a开发者_如何学运维ll the instances of this class, in objective-c?:

@interface Class1 : NSObject {
    NSString* shared; /** shared among instance (this is not, but defined somehow) **/
    NSString* non_shared; /** other parameters non shared **/
}

In the program then, each instance of Class1 has its own non_shared variables (as usual), but all access the same shared one (when one instance changes it all can see it).

One possibility is to hide the variable as a property and use a singleton in the setter/getter functions, but I don't know if there is a simple way.

Thanks, Edu


Class variables (called static in many other OOP languages) are actually a bit of a pain in Objective-C. You have to declare a static global variable in the class' module (.m) file and reference that variable. You should add class-level getter/setters to encapsulate access to the static global variable. Your getter can alloc/init an object and put it in the variable if it is uninitialized before returning it.

If the static variable holds an instance (e.g. an NSString instance in your example), you need to make sure it doesn't get alloc/initialized more than once. Take a look at dispatch_once if you're on OS X 10.6 or greater to guarantee single initialization.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜