Objective C Static Class Level variables

2018-12-31 23:26发布

I have a class Film, each of which stores a unique ID. In C#, Java etc I can define a static int currentID and each time i set the ID i can increase the currentID and the change occurs at the class level not object level. Can this be done in Objective C? I've found it very hard to find an answer for this.

9条回答
美炸的是我
2楼-- · 2019-01-01 00:19

Here would be an option:

+(int)getId{
    static int id;
    //Do anything you need to update the ID here
    return id;
}

Note that this method will be the only method to access id, so you will have to update it somehow in this code.

查看更多
谁念西风独自凉
3楼-- · 2019-01-01 00:20

Another possibility would be to have a little NSNumber subclass singleton.

查看更多
人气声优
4楼-- · 2019-01-01 00:22

(Strictly speaking not an answer to the question, but in my experience likely to be useful when looking for class variables)

A class method can often play many of the roles a class variable would in other languages (e.g. changed configuration during tests):

@interface MyCls: NSObject
+ (NSString*)theNameThing;
- (void)doTheThing;
@end
@implementation
+ (NSString*)theNameThing { return @"Something general"; }
- (void)doTheThing {
  [SomeResource changeSomething:[self.class theNameThing]];
}
@end

@interface MySpecialCase: MyCls
@end
@implementation
+ (NSString*)theNameThing { return @"Something specific"; }
@end

Now, an object of class MyCls calls Resource:changeSomething: with the string @"Something general" upon a call to doTheThing:, but an object derived from MySpecialCase with the string @"Something specific".

查看更多
登录 后发表回答