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:
- that second assignment self in init looks weird, not insane. or it?
- is wishful coding think second alloc (of instance1) gets magically cleaned up?
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.see #1.
Comments
Post a Comment