I want to declare a static int variable in one class and have access to it in every other class. What is the best way to do this?
相关问题
- 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
How about using a singleton class to save all the variables which any class can access and scope is the entire runtime of the app. Check out this link
Here are some ways you could try
Declaring the global variables in appdelegate
Creating a singleton class and putting the global variables there.
Using appdelegate
appdelegate is also a kind of singleton class
Function definition:
Function Calling:
Using your own singleton class
Only one instance of class can exist.
Sample singleton declaration:
Sample singleton implementation:
Approach 1: Using GCD
Approach 2: Without using GCD
Function definition:
Function Calling:
NSString to int:
As far as I’m aware, there are no performance issues with doing it one way over another.
I always prefer singleton class rather than appdelegate because the code will be clutter free and I consider overusing appdelegate as smelly code.
There are no static class variables in Objective C. You can create it as a file-scope static variable in the class' implementation file and provide static setter and getter methods in the class.
Or you can make it an old-school global, with an
extern
declaration in the .h file. The former approach is more flexible - you can add extra checks in the setter method, for example, the latter is less typing, and avoids the method call overhead.That breaks some patterns, I'd not use it.
Anyway, if you declare a property in your app delegate then you can call:
[[NSApp delegate] myVar]
anywhere.How exactly do you intent to use this variable?