I want store a number as a global variable. What syntax do I use, and how can other parts of my application access that variable?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- back button text does not change
- iOS (objective-c) compression_decode_buffer() retu
- how to find the index position of the ARRAY Where
相关文章
- 现在使用swift开发ios应用好还是swift?
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- didBeginContact:(SKPhysicsContact *)contact not in
- Custom Marker performance iOS, crash with result “
- Why is my library not able to expand on the CocoaP
To make a Variables that can be seen by the whole files in Objective c
for example you want to set your base url one time and in each class you append on it some extra strings,
go to main.m file, because this is the place the whole app will see it. then outside main function, put your base url
and when you want to access these class, all what you will do is this,
SomeClass.m
with the same name in both ;)
For a standard global variable (not persistent when the app is terminated and restarted) add this to a header file (*.h) of your choice:
Then put this in the implementation file; (*.m, *.c, *.cpp):
That is how you do a bread and butter global variable.
You probably want to use NSUserDefaults for this :
From anywhere in your code, you can set a value for a key :
And get it back from any other place :
You can also set an initial value :
Also, if you have complex data, you may want to create a wrapper class with setters and getters.
For persistent vars, use NSUserDefaults. This gets written on a file in the app sandbox. For session vars (non-persistent), I use a singleton class with an NSMutableDictionary property to store variables.
To declare a global variable in either objective-C or Swift, you simply declare it outside the scope of any class/interface.
Objective-C:
Swift:
Define the variable in AppDelegate.h file. Create a property in .h file
Then synthesize in AppDelegate.m file;
Later define a variable in you project prefix.pch file
Use the value anywhere in your project