Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C, member variables and class variables

i need some help on understanding how to use class/member variable from a instance method in Objective-C.

Any snipplet / example is highly appreciated.

Thanks.

like image 462
Garry.S Avatar asked Jan 18 '11 20:01

Garry.S


People also ask

How do you declare a class variable in Objective-C?

The declaration of a class interface begins with the compiler directive @interface and ends with the directive @end . (All Objective-C directives to the compiler begin with “@”.) // Method and property declarations. The first line of the declaration presents the new class name and links it to its superclass.

What is a class member variable?

A class variable is an important part of object-oriented programming (OOP) that defines a specific attribute or property for a class and may be referred to as a member variable or static member variable.

What is instance variable Objective-C?

An instance variable is a variable that exists and holds its value for the life of the object. The memory used for instance variables is allocated when the object is first created (through alloc ), and freed when the object is deallocated.

What does @() mean in Objective-C?

In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals. '@' is used a lot in the objective-C world.


1 Answers

Objective-C doesn't have class variables, and what you call a member variable is called an instance variable. Instance variables can be referenced by name from within an instance method. And if you need the behavior of a class variable, you can use a file-level static instead.

Here's a very quick sample:

Foo.h

@interface Foo : NSObject {
    NSString *foo;
}
@end

Foo.m

static NSString *bar;

@implementation Foo
- (void)foobar {
    foo = @"test"; // assigns the ivar
    bar = @"test2"; // assigns the static
}
@end
like image 50
Lily Ballard Avatar answered Sep 29 '22 12:09

Lily Ballard