Possible Duplicate:
Where do I have to declare static variables?
I've seen code like
@implementation ClassA
static NSString *str = nil;
.....
@end
as well as
static NSString *str = nil;
@implementation ClassA
.....
@end
What's the difference if a static var is declared inside the @implmentation context vs outside
Always static variables defines outside the class. Because if we define inside the class, then you need the object of that class to access that variable. If you create anything outside the class, no need to create object. So To access the static variable, you don't need to create object.
In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program. This is in contrast to automatic variables, whose lifetime exists during a single function call; and dynamically-allocated variables like objects, which can be released from memory when no longer used.
Yes it is. Each of your b variables is private to the function in which they are declared. Show activity on this post. b in func and b in main are two different variables, they are not related, and their scope is inside each function that they are in.
static. The static keyword can be used to declare variables and functions at global scope, namespace scope, and class scope. Static variables can also be declared at local scope. Static duration means that the object or variable is allocated when the program starts and is deallocated when the program ends.
There is no difference between
@implementation ClassA
static NSString *str = nil;
.....
@end
and
static NSString *str = nil;
@implementation ClassA
.....
@end
They work the same way ...
Static variables help give the class object more functionality than just that of a "factory" producing instances; it can approach being a complete and versatile object in its own right. A class object can be used to coordinate the instances it creates, dispense instances from lists of objects already created, or manage other processes essential to the application. In the case when you need only one object of a particular class, you can put all the object's state into static variables and use only class methods. This saves the step of allocating and initializing an instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With