Static variable in ObjectiveC - iphone

Static variables are variables allocated statically at compile time. My doubt is for what purpose some variables are declared statically? I didn't have used any static variable in my code till now. From the apple code http://developer.apple.com/library/ios/#samplecode/CryptoExercise/Introduction/Intro.html
in securityWrapper.m, there is a line
static SecKeyWrapper * __sharedKeyWrapper = nil;
what is the use of statically allocating __sharedKeyWrapper here?
I have seen the use of static key word in so many codes. So kindly explain the use and benefits when static keyword.
Thanks in advance.

That file global is a singleton, used for sharing an instance of a class.
The reason it's static in Objective-C is internal linkage. In practice, this means the variable can not be seen outside the file it is declared in. If another file declares a variable with the same name, they're two different variables.
Keep in mind that the way Objective-C instances work, the instance won't actually be allocated automatically. Rather, you have a pointer to the instance. The code will still have to do something like:
if ( !_sharedKeyWrapper ) {
_sharedKeyWrapper = [[SecKeyWraper alloc] initBlahBlah];
}
See links for more.

When you define a new class of objects, you can decide what instance
variables they should have. Every instance of the class will have its
own copy of all the variables you declare; each object controls its own
data.
However, you can't prescribe variables for the class object; there are
no "class variable" counterparts to instance variables. Only internal
data structures, initialized from the class definition, are provided for
the class. The class object also has no access to the instance variables
of any instances; it can't initialize, read, or alter them.
Therefore, for all the instances of a class to share data, an external
variable of some sort is required. Some classes declare static variables
and provide class methods to manage them. (Declaring a variable static
in the same file as the class definition limits its scope to just the
class-and to just the part of the class that's implemented in the file.
Unlike instance variables, static variables can't be inherited by
subclasses.)
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.

Also static variables are initialized once. You can use static variables in recursive calls. Simple Example Factorial.

Related

What are some use cases for static methods and properties in classes?

PowerShell classes can contain static methods and properties:
class stack {
[string]
$name
[DateTime]
static $date = (GET-DATE)
stack($name) {
$this.name = $name
}
static [void] hello() {
Write-Host 'hello'
}
}
A couple use cases I've found so far for static methods:
organize my functions within a common context of a class.
I believe I have read somewhere that static methods are much more performant than functions. I've never verified it myself, though.
And for static properties:
They define variables that can be called from any scope, especially from within other classes without needing to pass the variable into the class as an argument.
I have the feeling that my reasons for using static methods / properties are pretty underdeveloped. Static properties in particular seem like more laborious alternatives to simple variables, although the omni-scope availability is very nice if you do run into that use case.
So my questions:
What use cases have you found for static methods/properties?
Does it ever make sense to set a static property without a default value?
Since PowerShell was given, I will give a .NET-centric answer.
Ultimately the details will vary from language to language, but static class instances are typically instantiated only once the first time a static member is called on it. This means you will have a single instance created for any code which needs to call it. Conversely, being able to call the constructor of a non-static class means you can create as many instances as times you can call the constructor. For classes with both static and non-static members, the static members are still only created a single time in memory for the static instance.
Create static methods if the method does not rely on instance data to get the job done. For example, a string class might include static utility methods that still require a source string to be passed in. Let's look at the signature of the built-in String.IsNullOrEmpty static method:
[string]::IsNullOrEmpty
# OverloadDefinitions
# -------------------
# static bool IsNullOrEmpty(string value)
IsNullOrEmpty makes sense to define as static because it does not make sense to have it operate on an instantiated string object instead. Think about what the method does. It checks for:
A null value; or
A value of [string]::Empty
It is a utility method in order check the conditions above against another string. If this were not a static method, we cannot check for a null string as the instance doesn't exist(you can't call a method on a null-valued expression). Even if we could have a null string and call the method, we would first need to create a string object to use it, which would allocate memory for IsNullOrEmpty for every single string object. None of this is efficient considering it's a utility method that can easily have a valid string passed into it.
The main benefit here is that you do not need to allocate memory for every static method for every string object created. As explained above, the static methods are instantiated only once for the static instance.
The same goes for properties, although oftentimes static properties are read only. One example might be a System Properties class, and the OS version may be a static string. Consider the static property I used above, [string]::Empty. If this were not a static property, we run into the same pitfalls as defining IsNullOrEmpty as a non-static member: it will get allocated more often than it needs to be, and we need to first create a non-null instance to use it. The latter occurs with static classes behind the scenes, so you are free to use static members without worrying about initialization or instantiation.
Note: Create a static class if all the members are planned to be static, as it does not make sense to create an instance when it would hold no stateful information. Static classes in .NET are classes that cannot be directly instantiated, except for a single static constructor.
To summarize, it's mostly about memory management. Static members are only created once during the lifetime of the program, while instance (non-static) members are created for each instance of the object created with new.

Difference between objects, attributes, variables and class instance

I am having trouble understanding my professor's lecture notes because my brain seem to treat objects, attributes, variables and class instance as interchangeable. I really appreciate any help in distinguishing these 4 terms. Thank you!
this would be helpful for u Visit https://www.quora.com/What-is-the-difference-between-instance-variable-and-class-variable
Class variables are declared with keyword static and Instance variables are declared without static keyword.
Class variables are common to all instances of a class. These variables are shared between the objects of a class. Instance variables are not shared between the objects of a class. Each instance will have their own copy of instance variables.
As class variables are common to all objects of a class, changes made to these variables through one object will reflect in another. As each object will have its own copy of instance variables, changes made to these variables through one object will not reflect in another object.
Class variables can be accessed using either class name or object reference. Instance variables can be accessed only through object reference.
https://qph.fs.quoracdn.net/main-qimg-c4b92e80a8500c11fe705c1bafc3ed26
You don't mention the programming language at question.
Usually a class is a model or template that declares
how a certain category of objects look like.
You give a class a name and you mention if it inherits
members from another class or not.
You define also the class members.
These can be variables that hold data (object state)
and methods (class defined functions) that define
the object behaviour.
When you instantiate a class using the declared model
, you get an object, that is a concrete class instance.
This is a concrete entity, think of it as a new variable in memory,
whose data type is the class (instead of for example
integer or string data types), whose value is its state
in a defined moment in time (the state being the
combination of all of its data member variables values
at that moment). This object has to have an identity,
because it exists in memory and it is a different entity
from the other objects you can instantiate from this or
any other class. The data member variables hold specific
values for each instance. These are not shared between
instances.
Now the member methods can be shared between instances
because they have no state, so they are equal for every object.
They are called with some arguments
and they do some action that changes the object state, or
is at least tightly related with the concrete object.
But they are common to every object. The methods usually
know what concrete object they act upon by means of a special
name like 'this' or 'self', that references to 'itself'.
Objects are usually assigned to variables upon creation,
storing a reference to its identity that allows the
remaining code to manipulate them.
You use these variables to refer to the concrete object
outside the code of the classes, and use 'this' or 'self'
to refer to it from inside the classes.
Frequently you access object members qualifying with the
object name. Like in 'player.run()', or 'player.total_score'.
That is if player is a variable to which you assigned a
class Player instance. This can look like player = new Player
or player = Player().
Attributes is just another name given to data members.
Sometimes attributes and also methods can be public or private,
meaning code outside the class can use them, or only
the class code can have access.
Sometimes you see data members or attributes referred as
properties. When you access an attribute, you are accessing
a property. In some languages like Python, property can mean
something a little different but close related anyway...
Now also depending on the language things can be like described
(C++, Java) or you can have everything being treated as objects,
including the class definitions (Python).
You should also search the internet or SO about
inheritance, overriding, class diagrams, and other things class
related.
This is all no more than the ability of defining your own data types
beoynd the language builtin types.
You can think of variables as names for boxes (memory containers in a certain address) holding values. But sometimes you want to manipulate
not the values but the addresses themselves. This time you say you have
references (to addresses). Sometimes variables are just names for those
references. References are also known as pointers. But you could do math with pointers (increment, decrement, add a fixed value to...) that you usually don't do with references.

Does the local keyword on methods imply automatic storage?

What storage policy will variables declared in a local function inside a class have, static or automatic?
The "storage policy" is the lifetime. It will always be automatic. Section 8.6 of IEEE 1800-2012 states
The lifetime of methods declared as part of a class type shall be automatic. It shall be illegal to declare a
class method with a static lifetime.
You can declare a class method as being static, but in that context it means something entirely different. Section 8.10 states:
A static method is different from a task with static lifetime. The former refers to the lifetime of the method
within the class, while the latter refers to the lifetime of the arguments and variables within the task.
So, a static method can be called even if no objects of that class exist.
The local or protected attribute of a class member has no effect on the storage policy. It only affects the visibility of the identifier used to access the members.
That being said, the storage policy of a class member also affects the visibility of that identifier. So both features have the ability to restrict access, but for different reasons.
For example, you can never access an automatic variable from outside the scope of where it was declared. It does not matter if that scope is a class method, or a simple task. And it does not matter what the default lifetime of that scope was.
Conversely, if you declare a static variable in a scope, you might be able to access that variable from outside that scope, but you need to consider all the other visibility rules.

Swift: class func .... why use this instead of func when creating a method inside a class?

I'm new to coding, apologies for dumb question.
Am following a tutorial to build a note taking app using Swift in Xcode.
Within a class definition I have been defining methods using the keyword func myMethod etc. At one point the instructor decides to define a Class method (within the existing class) using class func myMethod.
Why would you do this?
Thanks in advance for any feedback.
By defining a class method it means that you don't need an instance of that class to use the method. So instead of:
var myInstance: MyClass = MyClass()
myInstance.myMethod()
You can simply use:
MyClass.myMethod()
The static (class) function is callable without needing an instance of the class available; it may be called without having to instantiate an object.
This can be useful for encapsulation (avoiding placing the function in the global namespace), or for operations that apply to all objects of a given class, such as tracking the total number of objects currently instantiated.
Static functions can be used to define a namespaces collection of related utility functions:
aDate = Utils.getDate()
aTime = Utils.getTime()
Another common use is for the singleton pattern, where a static function is used to provide access to an object that is limited to being instantiate only once:
obj = MySingleton.getInstance()
obj.whatever()
One answer is namespacing. If a function is only relevant to a certain class there is no need to declare the function globally.
This is Swift's take on static methods:
Static methods are meant to be relevant to all the instances of a class (or no instances) rather than to any specific instance.
An example of these are the animation functions in UIView, or the canSendMail function from MFMailComposeViewController.

Modelica : variables of class during instantiation

The variables of Modelica classes are instantiated per object.
Can anyone clarify this statement?
First of all Modelica has only one type of object, the class, and the other objects (model, record, package) are only special types of class with restrictions. That means that every object must follow the same rules, therefore I'll refer to the object class, but what I'll write will apply to every Modelica object.
The variables are instantiated per object means that if you have a Modelica class like the following one:
partial class MySimpleClass
Real variable1;
equation
variable1 = time;
end MySimpleClass;
When you declare a member variable such as MySimpleClass in instanceOfTypeMySimpleClass:
class mySecondClass
MySimpleClass instanceOfTypeMySimpleClass;
MySimpleClass instanceTwoOfTypeMySimpleClass;
Real variable1;
equation
variable1 = instanceOfTypeMySimpleClass.variable1;
instanceTwoOfTypeMySimpleClass.variable1 = 3;
end mySecondClass;
you declare an instance variable. Every time you create an instance of a class, the Modelica compiler creates one copy of each the class's instance variables for the instance and this is done by objects. You can access an object's instance variables from an object using the syntax <instanceName>.<VariableName>.
The Modelica compiler allocates class variables once per instance. The The Modelica compiler allocates memory for class variables every time it encounters an instance of that class. Therefore all instances DID NOT share the same copy of the class's class variables as, for example, for static classes in Java. In other words in this example instanceOfTypeMySimpleClass.variable1 and instanceTwoOfTypeMySimpleClass.variable1 are two different variables.
"The variables of Modelica classes are instantiated per object." meant to describe this difference.
I hope this helps,
Marco