Objective-C, member variables and class variables

2020-03-03 04:16发布

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.

1条回答
姐就是有狂的资本
2楼-- · 2020-03-03 05:15

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
查看更多
登录 后发表回答