开发者

Sharing a variable between all instances of one class

开发者 https://www.devze.com 2023-02-04 00:22 出处:网络
Hey, I am making a imageloading system with my tablecells and I need each cell to share the same instance of my imageloader class. Sorry if this is a nooby question, but is it possible to a开发者_开发

Hey, I am making a imageloading system with my tablecells and I need each cell to share the same instance of my imageloader class. Sorry if this is a nooby question, but is it possible to a开发者_开发百科rchieve this? So what I am meaning is that if I have int variable in other instance of the same class, the value of the int variable is same in both classes.

Thanks in advance!


For a "single instance for everything", you need a singleton:

+(SomeClass *)sharedInstance {
  static SomeClass *instance = nil;
  if (instance == nil) {
    instance = [[self alloc] init];
  }
  return instance;
}

Then wherever you need the shared instance, just do:

SomeClass *obj = [SomeClass sharedInstance];

The static variable is basically what makes it work, when coupled with the "is nil" test, since static variables are only ever initialized once.

Incidentally, I think due to the way UITableViewCells are used (i.e. copied) you may already have what you need without any further work such as creating a singleton. Just provide the correct shallow-copy logic in copyWithZone:.

0

精彩评论

暂无评论...
验证码 换一张
取 消