objective c - Mutable List of instances of one specific class -
this question has answer here:
i want keep track of variable amount of objects in game, instances of same class or inheriting classes, in objective-c.
in java like
list<myclass> list = new arraylist<>();
and it. couldn't find obvious solution using cocoa / foundation. can use nsmutablearray in way? note, need objects of specific type want them be, not id. prefer not having use categories or inherit nsmutablearray, instead use nsmutablearray in way returns cast class need.
objective-c not have generics, nsarray , nsmutablearray not typed in way desire. it's pretty simple work around though. given following code, have nsmutablearray named list
item in of type myclass
:
nsmutablearray *list = [nsmutablearray new]; myclass *objecttoinsert = [myclass new]; [list addobject:objecttoinsert];
to retrieve object array , treat pointer type myclass
, declare variable such:
myclass *myobject = list[0]; myobject.someproperty = somevalue; [myobject dosomething];
xcode offer full code completion, etc. note not need use c-style cast; can implicitly cast variable of type id
object pointer when declaring variable. can in loops:
for (myclass *item in list) { item.someproperty = somevalue; [item dosomething]; }
note in simple cases want pass objects around or maybe invoke 1 method, can leave object of type id
if you're comfortable that.
[list[0] dosomething];
the above still send message dosomething
object of type myclass , invoke proper method on object, assuming object in array of correct type. there no distinction @ runtime between doing , more explicit syntax shown earlier.
note compiler or runtime will not check items in array of type myclass. thus, can unexpected behavior or runtime errors if insert other types of objects array. in experience, isn't of risk code.
also, mentioned in comments, create custom class "strongly typed" convenience methods populate , access nsmutablearray. methods signatures - (void)addwidget:(mywidget *)obj
or - (void)insertwidget:(mywidget *)obj atindex:(nsinteger)index
allow xcode check type of objects inserted array @ compile time in not cases (if have variable of type id
, can still use these methods without compile-time warnings or errors, allowing insertion of objects of other types). if want more defensive it, add assertion these methods check type @ runtime:
- (void)addwidget:(mywidget *)obj { nsassert([obj iskindofclass:[mywidget class]]); [self.list addobject:obj]; }
in experience though find more effort it's worth, unless have significant logic associate manipulation of array.
note swift have full implementation of generics.
Comments
Post a Comment