ios - class tracking and limiting instances with an NSSet -


i'd class detect new instance equivalent (vis vis isequal: , hash) existing instance, , create unique instances. here's code think job, i'm concerned it's doing dumb can't spot...

say it's nsurlrequest subclass this:

// myclass.h @interface myclass : nsmutableurlrequest @end  // myclass.m  @implementation myclass  + (nsmutableset *)instances {      static nsmutableset *_instances;     static dispatch_once_t once;      dispatch_once(&once, ^{ _instances = [[nsmutableset alloc] init];});     return _instances; }  - (id)initwithurl:(nsurl *)url {      self = [super initwithurl:url];     if (self) {         if ([self.class.instances containsobject:self])             self = [self.class.instances member:self];         else             [self.class.instances addobject:self];     }     return self; }   // caller.m nsurl *urla = [nsurl urlwithstring:@"http://www.yahoo.com"];  myclass *instance0 = [[myclass alloc] initwithurl: urla]; myclass *instance1 = [[myclass alloc] initwithurl: urla];  // 2  bool works = instance0 == instance1;  // works => yes, @ hidden cost? 

questions:

  1. that second assignment self in init looks weird, not insane. or it?
  2. is wishful coding think second alloc (of instance1) gets magically cleaned up?

  1. it's not insane, in manual retain/release mode, need release self beforehand or you'll leak uninitialized object every time method run. in arc, original instance automatically released you.

  2. see #1.

btw, readers stop @ 1 answer, bbum's answer below includes full working example of thread-safe implementation. highly recommended making class this.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -