13

I have classes A and B.
Can I put these classes in the same NSMutableArray without problems in future?

Example:

NSMutableArray *maincoll = [[NSMutableArray alloc] init];
ClassA *ca = [[classA alloc] init];
ClassB *cb = [[classB alloc] init];
//here is case
[maincoll addObject:ca];
[maincoll addObject:cb];
...
Fish
  • 173
  • 1
  • 6

3 Answers3

27

Yes. No limitations. The only thing you have to be careful of is when you retrieve items from the array to verify their class (if necessary) before starting to use them.

pmeyer
  • 643
  • 1
  • 5
  • 10
  • ANd how do you verify their classes? – Cypress Frankenfeld Aug 22 '13 at 16:34
  • google: "objective-c find class of object". First hit: http://stackoverflow.com/a/2056036 Summary: "[yourObject isKindOfClass:[a class]]" – pmeyer Aug 22 '13 at 21:33
  • The for loop can do this for you. For example with a NSArray *containter: for (NSString *string in container) { // do whatever }; goes in and takes all the NSString objects and does something and then you can do: for (NSWhatever *whatever in container) { // do something else }; – unom Feb 11 '14 at 07:46
8

Yes.

This may be the shortest answer I've ever posted.

jrturton
  • 118,105
  • 32
  • 252
  • 268
0

You can put objects of different classes. They just need to inherit from NSObject. Don't forget to release after adding to the array.

jbat100
  • 16,757
  • 4
  • 45
  • 70
  • No, they don't need to inherit from `NSObject`. They just need to be Objective-C objects, i.e. of `id` type. – mouviciel Oct 26 '11 at 13:31
  • I'll phrase my comment as a question, can you ensure that id types will respond to retain/release messages? from what I understand you can't. – jbat100 Oct 26 '11 at 13:47
  • They don't need to. Check `addObject:` prototype in [NSMutableArray Reference](http://developer.apple.com/library/IOS/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html) – mouviciel Oct 26 '11 at 13:57
  • You're right as the definition for addObject: is - (void)addObject:(id)anObject. If you do insert an id type which doesn't inherit from NSObject, is it your responsibility to ensure that it responds to the retain/release messages the array will send to it, or will the NSArray know not to. – jbat100 Oct 26 '11 at 13:59
  • @mouviciel, the interface does say `id`, but if you try to add an object that doesn't implement the `NSObject` protocol to a `NSArray`, the `addObject:` call will throw an exception. You can easily try with a `Class` object: `[array addObject:[NSArray class]];` – zneak Oct 27 '11 at 17:04