Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between declaring static variable inside and outside the implementation context in Objective C? [duplicate]

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

like image 937
blueether Avatar asked Apr 26 '11 06:04

blueether


People also ask

Why static variable is declared outside the class?

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.

What is static variable in Objective-C?

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.

Can static variables be declared twice?

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.

Are variables in namespace static?

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.


1 Answers

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.

like image 180
Viktor Apoyan Avatar answered Oct 12 '22 10:10

Viktor Apoyan