I'm making an program, and it requires that properties in one View Controller be accessible by all classes. How would I make a global property?
-
Can't have a global property really unless you put it in the app delegate, which you shouldn't. Take look at this question the answer will show how to make a static helper. http://stackoverflow.com/questions/8647331/global-property-in-objective-c – BooRanger Aug 29 '13 at 13:27
-
Would someone tell me why that keep voting my posts down? It gets really annoying when I don't know what to change. – DonyorM Aug 30 '13 at 01:33
-
because you didn't search first, this question has been answered before. – BooRanger Aug 30 '13 at 08:22
-
I did do some searching, but as you said, not enough. I didn't see anything that had to do with properties though, just variables. – DonyorM Aug 30 '13 at 08:30
1 Answers
A couple of options:
Ideally, you should avoid making it a global, but rather pass the property from one view controller. See this excellent answer for examples (such as setting it in
prepareForSegue
).Alternatively, you can create a singleton, and make your property of that singleton. For example,
Model.h
:// Model.h @import Foundation; NS_ASSUME_NONNULL_BEGIN @interface Model : NSObject @property (class, strong, readonly) Model *sharedModel; @property (nonatomic, copy, nullable) NSString *myString; - (id)init __attribute__((unavailable("Use +[Model sharedModel] instead"))); + (id)new __attribute__((unavailable("Use +[Model sharedModel] instead"))); @end NS_ASSUME_NONNULL_END
and
Model.m
// Model.m #import "Model.h" @implementation Model + (instancetype)sharedModel { static id sharedMyModel = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedMyModel = [[self alloc] init]; }); return sharedMyModel; } @end
and then your various controllers can use this singleton class and reference that property you need accessible from other classes, such as:
#import "SomeViewController.h" #import "Model.h" @implementation SomeViewController - (void)viewDidLoad { [super viewDidLoad]; Model *model = [Model sharedModel]; model.myString = @"abc"; } @end
and
#import "AnotherViewController.h" #import "Model.h" @implementation AnotherViewController - (void)viewDidLoad { [super viewDidLoad]; NSString *string = [[Model sharedModel] myString]; // Do whatever you want with the string } @end
Your app actually already has a singleton, the app delegate, and you could add a property to that, and use that. For example, if you defined a property,
someOtherString
in the app delegate's .h, you could then reference it like so:AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; appDelegate.someOtherString = @"xyz";
If I'm going to use a singleton for model data, I prefer to create my own, but this is another approach that some people use.

- 415,655
- 72
- 787
- 1,044
-
Thanks for helping, I see now that I may just use global variables, which are easier. Thanks anyway. – DonyorM Aug 30 '13 at 01:32