8

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.

nevan king
  • 110,877
  • 44
  • 200
  • 239
Garry.S
  • 201
  • 1
  • 3
  • 9

1 Answers1

17

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
Lily Ballard
  • 176,187
  • 29
  • 372
  • 338
  • And you will use it like : Foo *myFoo = [[Foo alloc] init]; [myFoo foobar]; [myFoo release]; – nacho4d Jan 18 '11 at 20:19
  • Thanks for your fast respone, my idea is to have a class NSMutableDictionary that all instances of a object shares, would that be a correct way of design or im I missing something? – Garry.S Jan 18 '11 at 20:36
  • 1
    If you need a shared dictionary, that works fine. You'd want a file-level static in the .m for the NSMutableDictionary, and you'll likely want to create it in your `+initialize` method (to ensure it exists before any instances access it). If you ever need to touch this object off of the main thread, you should use a GCD dispatch queue to serialize access to it - otherwise, just go ahead and use it like normal. Note that you'll need to stick an owned instance in the variable, e.g. `[[NSMutableDictionary alloc] init]`. And never release it (as the class itself never goes away). – Lily Ballard Jan 18 '11 at 21:58