0

Is there any way to specify what specific type of object can be contained within an NSMutableArray?

EDIT More specifically... Is there a way to restrict the class that the object must belong to?

7
  • An NSMutable array can hold any type of object and can hold different types of objects at one time. Can you be more specific? Do you need help adding objects of different types to the NSMutableArray? Specifying an object type when getting it from the array? Commented May 22, 2012 at 1:03
  • Is there a way to restrict the class that the object must belong to? Commented May 22, 2012 at 1:08
  • Yes, use a Obj-C++ vector<T *>. Because ObjC is a dynamically typed language, it is extremely difficult to create something like this (but not impossible). This is because any object at any time can say it's another object, and the runtime has to believe it. Commented May 22, 2012 at 1:13
  • 2
    Why is this necessary? You control what you add to the array, don't you? If you elaborate on why you need this functionality, I'm sure someone will be able to suggest a way to accomplish the same effect. Commented May 22, 2012 at 1:14
  • 1
    possible duplicate of Is there any way to enforce typing on NSArray, NSMutableArray, etc.? Commented May 22, 2012 at 3:47

2 Answers 2

2

Well, you could always subclass NSMutableArray but as everyone else has said, it is hard to imagine a good reason to do this....

From Subclassing Notes in the docs you would basically have to over-ride the following functions and check for the proper class:

  • insertObject:atIndex:
  • addObject:
  • replaceObjectAtIndex:withObject:
  • the primitive methods of the NSArray class
Sign up to request clarification or add additional context in comments.

1 Comment

I ended up subclassing it and modifying all the methods as described here. Thanks so much!
1

You could check the class of the object before adding it to the array.

NSMutableArray *myArray = [NSMutableArray alloc] init];

if ([someObject isKindOfClass:[ClassYouWantInArray class]]){

    [myArray addObject:someObject];
}

1 Comment

You could add a class category too, to "addSomeObject" and verify it this way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.