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.
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.
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.
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.
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.
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
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