Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to store `Class` object into `NSMutableArray`?

The type Class is not look Objective-C type. So storing it into NSMutableArray looks need special care. What's the correct way to do this?

like image 937
eonil Avatar asked Dec 05 '25 16:12

eonil


2 Answers

Class objects are just like other objects. You can definitely store them in a NSMutableArray or do things with them as you would normally do with objects (e.g. call the methods of the root class NSObject, like description and performSelector..., etc.) Note that the type Class is a generic type for pointers to class objects, similar to how the type id is a generic type for pointers to objects. So a value of type Class can also be passed as an id.

NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[yourObject class]];
[array addObject:[anotherObject class]];

//Later in your code.

Class yourObject = [array objectAtIndex:0UL];
like image 183
user102008 Avatar answered Dec 08 '25 08:12

user102008


I dont know the "correct way" but can't you store it as a string?

NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:NSStringFromClass([yourObject class])];
[array addObject:NSStringFromClass([anotherObject class])];

//Later in your code.

id yourObject = NSClassFromString([array objectAtIndex:0UL]);

Hope it might help.

like image 42
Konrad77 Avatar answered Dec 08 '25 06:12

Konrad77



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!