0

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 archieve 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!

Samuli Lehtonen
  • 3,840
  • 5
  • 39
  • 49

1 Answers1

2

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

d11wtq
  • 34,788
  • 19
  • 120
  • 195