Can I make a NSMutableArray
instance where all the elements are of type SomeClass
?

- 18,845
- 10
- 77
- 85

- 7,049
- 10
- 42
- 47
-
the same question: http://stackoverflow.com/questions/5197446/nsmutablearray-force-the-array-to-hold-specific-object-type-only – Hugo Dec 19 '12 at 07:41
11 Answers
Nobody's put this up here yet, so I'll do it!
Tthis is now officially supported in Objective-C. As of Xcode 7, you can use the following syntax:
NSArray<MyClass *> *myArray = @[[MyClass new], [MyClass new]];
Note
It's important to note that these are compiler warnings only and you can technically still insert any object into your array. There are scripts available that turn all warnings into errors which would prevent building.

- 52,262
- 20
- 99
- 128
-
I am being lazy here, but why is this only available in XCode 7? We can use the `nonnull` in XCode 6 and as far as I remember, they were introduced at the same time. Also, does the usage of such concepts depend on the XCode version or on the iOS version? – Guven Jul 03 '15 at 12:08
-
@Guven - nullability came in 6, you are correct, but ObjC generics weren't introduced until Xcode 7. – Logan Jul 03 '15 at 14:17
-
I am pretty sure it depends on Xcode version only. The generics are compiler warnings only and are not indicated at runtime. I'm pretty sure you could compile to whatever Os you want. – Logan Jul 03 '15 at 14:19
-
Got it! Thanks for the detailed explanation. This actually should be the right answer as of XCode 7! – Guven Jul 03 '15 at 18:03
-
@Logan how would this look if instead of `MyClass *` you had an array of some unknown `id
` objects? Is that possible? – Dean Kelly Jul 06 '15 at 20:05 -
2@DeanKelly - You could do that like this: `@property (nonatomic, strong) NSArray
>* protocolObjects;` Looks a little clunky, but does the trick! – Logan Jul 06 '15 at 21:10 -
NSArray
*array = @[@"", @1]; NSLog(@"Array: %@", array); Array: ( "", 1 ) – adnako Sep 17 '15 at 13:10 -
@adnako - I'm not sure I understand your comment, but I believe you're demonstrating that although you type constrained to `NSString`, you inserted an `NSNumber`. I'll add this to the answer, but its important to remember that these constraints are compiler warnings only at the ObjC level. If you ignore them, the system will allow you to. – Logan Sep 17 '15 at 13:31
-
@Logan exactly - this is only clever compiler warnings. Runtime still as same as it was. – adnako Sep 18 '15 at 07:13
-
1@Logan, there is not only the set of scripts, that prevent building in case of any warning detected. Xcode has a perfect mechanism named "Configuration". Check this out http://boredzo.org/blog/archives/2009-11-07/warnings – adnako Sep 18 '15 at 07:20
-
I speculate `__kindof` might allow for subclasses? I noticed in the iOS 9.0 UINavigationController.h:64: `@property(nonatomic,copy) NSArray<__kindof UIViewController *> *viewControllers;` – tboyce12 Oct 08 '15 at 18:03
-
Is it possible to get somehow the information about the type in the array during runtime? e.g. using property_getAttributes does not work, it just returns NSArray. – Vladimír Slavík Dec 11 '16 at 19:14
This is a relatively common question for people transitioning from strongly type languages (like C++ or Java) to more weakly or dynamically typed languages like Python, Ruby, or Objective-C. In Objective-C, most objects inherit from NSObject
(type id
) (the rest inherit from an other root class such as NSProxy
and can also be type id
), and any message can be sent to any object. Of course, sending a message to an instance that it does not recognize may cause a runtime error (and will also cause a compiler warning with appropriate -W flags). As long as an instance responds to the message you send, you may not care what class it belongs to. This is often referred to as "duck typing" because "if it quacks like a duck [i.e. responds to a selector], it is a duck [i.e. it can handle the message; who cares what class it is]".
You can test whether an instance responds to a selector at run time with the -(BOOL)respondsToSelector:(SEL)selector
method. Assuming you want to call a method on every instance in an array but aren't sure that all instances can handle the message (so you can't just use NSArray
's -[NSArray makeObjectsPerformSelector:]
, something like this would work:
for(id o in myArray) {
if([o respondsToSelector:@selector(myMethod)]) {
[o myMethod];
}
}
If you control the source code for the instances which implement the method(s) you wish to call, the more common approach would be to define a @protocol
that contains those methods and declare that the classes in question implement that protocol in their declaration. In this usage, a @protocol
is analogous to a Java Interface or a C++ abstract base class. You can then test for conformance to the entire protocol rather than response to each method. In the previous example, it wouldn't make much of a difference, but if you were calling multiple methods, it might simplify things. The example would then be:
for(id o in myArray) {
if([o conformsToProtocol:@protocol(MyProtocol)]) {
[o myMethod];
}
}
assuming MyProtocol
declares myMethod
. This second approach is favored because it clarifies the intent of the code more than the first.
Often, one of these approaches frees you from caring whether all objects in an array are of a given type. If you still do care, the standard dynamic language approach is to unit test, unit test, unit test. Because a regression in this requirement will produce a (likely unrecoverable) runtime (not compile time) error, you need to have test coverage to verify the behavior so that you don't release a crasher into the wild. In this case, peform an operation that modifies the array, then verify that all instances in the array belong to a given class. With proper test coverage, you don't even need the added runtime overhead of verifying instance identity. You do have good unit test coverage, don't you?

- 6,031
- 2
- 38
- 83

- 107,306
- 24
- 181
- 206
-
36
-
8Yeah, who needs the tooling that typed arrays would afford. I'm sure @BarryWark (and anyone else who has touched any codebase that he needs to use, read, understand and support) has 100% code coverage. However I bet you don't use raw `id`s except where necessary, any more than Java coders pass around `Object`s. Why not? Don't need it if you've got unit tests? Because it's there and makes your code more maintainable, as would typed arrays. Sounds like people invested in the platform not wishing to concede a point, and therefore inventing reasons why this omission is in fact a benefit. – funkybro Aug 07 '13 at 15:56
-
You could make a category with an -addSomeClass:
method to allow compile-time static type checking (so the compiler could let you know if you try to add an object it knows is a different class through that method), but there's no real way to enforce that an array only contains objects of a given class.
In general, there doesn't seem to be a need for such a constraint in Objective-C. I don't think I've ever heard an experienced Cocoa programmer wish for that feature. The only people who seem to are programmers from other languages who are still thinking in those languages. If you only want objects of a given class in an array, only stick objects of that class in there. If you want to test that your code is behaving properly, test it.

- 234,037
- 30
- 302
- 389
-
138I think that 'experienced Cocoa programmers' just don't know what they're missing -- experience with Java shows that type variables improve code comprehension and make more refactorings possible. – tgdavies Nov 04 '10 at 16:52
-
12Well, Java's Generics support is heavily broken in it's own right, because they didn't put it in from the start... – dertoni Dec 08 '10 at 07:38
-
28Gotta agree with @tgdavies. I miss the intellisense and refactoring capabilities I had with C#. When I want dynamic typing I can get it in C# 4.0. When I want strongly types stuff I can have that too. I've found there is a time and place for both of those things. – Steve Jun 27 '11 at 04:34
-
There is a good degree of strong type checks in Objective-C. After awhile you will understand that you *DON'T* need such thing as generic NSArray. It's just not needed. period. Most of the time If you need it you havn't been programming in Objective-C long enough and just trying to fit your old programming model on a new language. People need to let go of things. (and yeah I have had many years of C# under my belt if that matters) – chakrit Jan 12 '12 at 06:09
-
18@charkrit What is it about Objective-C that makes it 'not necessary'? Did you feel it was necessary when you were using C#? I hear a lot of people saying you don't need it in Objective-C but I think these same people think you don't need it in any language, which makes it an issue of preference/style, not of necessity. – bacar Jan 30 '12 at 22:21
-
@bacar: Some languages have more restrictive static type systems, where things need to be typed correctly or you can't call their methods. – Chuck Jan 31 '12 at 00:19
-
1@Chuck hm. That's nothing you can't do with a cast though, right? I.e. that's not an argument for a stronger need for generics in statically typed systems. I believe people who like generics with static typing like it because it gives them extra safety, not because it reduces typing. – bacar Jan 31 '12 at 20:57
-
2@bacar: You can't cast unless you know the type of the receiver. My point is, Objective-C accesses everything through pointers that can be converted to any other type without complaint from the compiler. It is not a typesafe langauge. Generics would give you a little bit more type safety, but in a language as pervasively dynamic as Objective-C, it's a drop in the pond. The only other languages with dynamic typing as pervasive as Objective-C's don't have static type systems at all — JavaScript, Python, Ruby, etc. Neither Java nor C# was born with an `id` type — generics are their equivalent. – Chuck Apr 10 '12 at 18:07
-
17Isn't this about allowing your compiler to actually help you find problems. Sure you can say "If you only want objects of a given class in an array, only stick objects of that class in there." But if tests are the only way to enforce that, you are at a disadvantage. The further away from writing the code you find a problem, the more costly that problem is. – GreenKiwi May 24 '12 at 22:58
-
3@GreenKiwi: Yes, in a language with a type system that permits this, it can help you find problems. Objective-C does not have such a type system, so the degree to which the compiler can help you is limited. And in practice, this does not seem to be a very costly problem for most people. Since getting comfortable in Objective-C, how many hours have you spent debugging problems that arise from having heterogeneous arrays? Is it even one hour? I'm a fan of helpful static type systems, but Objective-C isn't such a language. At any rate, this is the correct answer for Objective-C, like it or not. – Chuck May 24 '12 at 23:17
-
1
-
@Chuck -- not true re: other languages with a basis in dynamic typing not having static type systems. See ActionScript3's Vector class, and also Haxe. http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Vector.html http://haxe.org/ – ericsoco Jan 28 '13 at 04:56
-
1It won't enforce contents, but _typedef NSMutableArray *SomeClassList_ at least helps with code readability and consistency (especially for return values and method parameters) and gives some compile-time warnings with very little overhead. – JohnQ Aug 14 '13 at 17:04
-
Definitely it is should be a feature of language. If it is not there, justifying its absence is not worthwhile. – Murtuza Kabul Aug 11 '14 at 15:17
-
1*So* not necessary, in fact... [that Apple added the feature, finally](http://stackoverflow.com/a/30719796/1366431). This answer no longer reflects official opinion on the matter (thank goodness). – Alex Celeste Jun 11 '15 at 21:06
-
You could subclass NSMutableArray
to enforce type safety.
NSMutableArray
is a class cluster, so subclassing isn't trivial. I ended up inheriting from NSArray
and forwarded invocations to an array inside that class. The result is a class called ConcreteMutableArray
which is easy to subclass. Here's what I came up with:
Update: checkout this blog post from Mike Ash on subclassing a class cluster.
Include those files in your project, then generate any types you wish by using macros:
MyArrayTypes.h
CUSTOM_ARRAY_INTERFACE(NSString)
CUSTOM_ARRAY_INTERFACE(User)
MyArrayTypes.m
CUSTOM_ARRAY_IMPLEMENTATION(NSString)
CUSTOM_ARRAY_IMPLEMENTATION(User)
Usage:
NSStringArray* strings = [NSStringArray array];
[strings add:@"Hello"];
NSString* str = [strings get:0];
[strings add:[User new]]; //compiler error
User* user = [strings get:0]; //compiler error
Other Thoughts
- It inherits from
NSArray
to support serialization/deserialization Depending on your taste, you may want to override/hide generic methods like
- (void) addObject:(id)anObject
-
Nice but for now it lacks strong typing by overriding some methods. Currently it's only weak typing. – Cœur Jul 22 '13 at 01:36
Have a look at https://github.com/tomersh/Objective-C-Generics, a compile-time (preprocessor-implemented) generics implementation for Objective-C. This blog post has a nice overview. Basically you get compile-time checking (warnings or errors), but no runtime penalty for generics.

- 107,306
- 24
- 181
- 206
-
1I tried it out, very good idea, but sadly buggy and it doesn't check the added elements. – Binarian Sep 26 '13 at 11:11
This Github Project implements exactly that functionality.
You can then use the <>
brackets, just like you would in C#.
From their examples:
NSArray<MyClass>* classArray = [NSArray array];
NSString *name = [classArray lastObject].name; // No cast needed

- 6,807
- 6
- 41
- 103
2020, straightforward answer. It just so happened that I need a mutable array with type of NSString
.
Syntax:
Type<ArrayElementType *> *objectName;
Example:
@property(nonatomic, strong) NSMutableArray<NSString *> *buttonInputCellValues;

- 12,555
- 6
- 54
- 95
I created a NSArray subclass that is using an NSArray object as backing ivar to avoid issues with the class-cluster nature of NSArray. It takes blocks to accept or decline adding of an object.
to only allow NSString objects, you can define an AddBlock
as
^BOOL(id element) {
return [element isKindOfClass:[NSString class]];
}
You can define a FailBlock
to decide what to do, if an element failed the test — fail gracefully for filtering, add it to another array, or — this is default — raise an exception.
VSBlockTestedObjectArray.h
#import <Foundation/Foundation.h>
typedef BOOL(^AddBlock)(id element);
typedef void(^FailBlock)(id element);
@interface VSBlockTestedObjectArray : NSMutableArray
@property (nonatomic, copy, readonly) AddBlock testBlock;
@property (nonatomic, copy, readonly) FailBlock failBlock;
-(id)initWithTestBlock:(AddBlock)testBlock FailBlock:(FailBlock)failBlock Capacity:(NSUInteger)capacity;
-(id)initWithTestBlock:(AddBlock)testBlock FailBlock:(FailBlock)failBlock;
-(id)initWithTestBlock:(AddBlock)testBlock;
@end
VSBlockTestedObjectArray.m
#import "VSBlockTestedObjectArray.h"
@interface VSBlockTestedObjectArray ()
@property (nonatomic, retain) NSMutableArray *realArray;
-(void)errorWhileInitializing:(SEL)selector;
@end
@implementation VSBlockTestedObjectArray
@synthesize testBlock = _testBlock;
@synthesize failBlock = _failBlock;
@synthesize realArray = _realArray;
-(id)initWithCapacity:(NSUInteger)capacity
{
if (self = [super init]) {
_realArray = [[NSMutableArray alloc] initWithCapacity:capacity];
}
return self;
}
-(id)initWithTestBlock:(AddBlock)testBlock
FailBlock:(FailBlock)failBlock
Capacity:(NSUInteger)capacity
{
self = [self initWithCapacity:capacity];
if (self) {
_testBlock = [testBlock copy];
_failBlock = [failBlock copy];
}
return self;
}
-(id)initWithTestBlock:(AddBlock)testBlock FailBlock:(FailBlock)failBlock
{
return [self initWithTestBlock:testBlock FailBlock:failBlock Capacity:0];
}
-(id)initWithTestBlock:(AddBlock)testBlock
{
return [self initWithTestBlock:testBlock FailBlock:^(id element) {
[NSException raise:@"NotSupportedElement" format:@"%@ faild the test and can't be add to this VSBlockTestedObjectArray", element];
} Capacity:0];
}
- (void)dealloc {
[_failBlock release];
[_testBlock release];
self.realArray = nil;
[super dealloc];
}
- (void) insertObject:(id)anObject atIndex:(NSUInteger)index
{
if(self.testBlock(anObject))
[self.realArray insertObject:anObject atIndex:index];
else
self.failBlock(anObject);
}
- (void) removeObjectAtIndex:(NSUInteger)index
{
[self.realArray removeObjectAtIndex:index];
}
-(NSUInteger)count
{
return [self.realArray count];
}
- (id) objectAtIndex:(NSUInteger)index
{
return [self.realArray objectAtIndex:index];
}
-(void)errorWhileInitializing:(SEL)selector
{
[NSException raise:@"NotSupportedInstantiation" format:@"not supported %@", NSStringFromSelector(selector)];
}
- (id)initWithArray:(NSArray *)anArray { [self errorWhileInitializing:_cmd]; return nil;}
- (id)initWithArray:(NSArray *)array copyItems:(BOOL)flag { [self errorWhileInitializing:_cmd]; return nil;}
- (id)initWithContentsOfFile:(NSString *)aPath{ [self errorWhileInitializing:_cmd]; return nil;}
- (id)initWithContentsOfURL:(NSURL *)aURL{ [self errorWhileInitializing:_cmd]; return nil;}
- (id)initWithObjects:(id)firstObj, ... { [self errorWhileInitializing:_cmd]; return nil;}
- (id)initWithObjects:(const id *)objects count:(NSUInteger)count { [self errorWhileInitializing:_cmd]; return nil;}
@end
Use it like:
VSBlockTestedObjectArray *stringArray = [[VSBlockTestedObjectArray alloc] initWithTestBlock:^BOOL(id element) {
return [element isKindOfClass:[NSString class]];
} FailBlock:^(id element) {
NSLog(@"%@ can't be added, didn't pass the test. It is not an object of class NSString", element);
}];
VSBlockTestedObjectArray *numberArray = [[VSBlockTestedObjectArray alloc] initWithTestBlock:^BOOL(id element) {
return [element isKindOfClass:[NSNumber class]];
} FailBlock:^(id element) {
NSLog(@"%@ can't be added, didn't pass the test. It is not an object of class NSNumber", element);
}];
[stringArray addObject:@"test"];
[stringArray addObject:@"test1"];
[stringArray addObject:[NSNumber numberWithInt:9]];
[stringArray addObject:@"test2"];
[stringArray addObject:@"test3"];
[numberArray addObject:@"test"];
[numberArray addObject:@"test1"];
[numberArray addObject:[NSNumber numberWithInt:9]];
[numberArray addObject:@"test2"];
[numberArray addObject:@"test3"];
NSLog(@"%@", stringArray);
NSLog(@"%@", numberArray);
This is just an example code and was never used in real world application. to do so it probably needs mor NSArray method implemented.

- 52,040
- 14
- 137
- 178
If you mix c++ and objective-c (i.e. using mm file type), you can enforce typing using pair or tuple. For example, in the following method, you can create a C++ object of type std::pair, convert it to an object of OC wrapper type (wrapper of std::pair that you need to define), and then pass it to some other OC method, within which you need to convert the OC object back to C++ object in order to use it. The OC method only accepts the OC wrapper type, thus ensuring type safety. You can even use tuple, variadic template, typelist to leverage more advanced C++ features to facilitate type safety.
- (void) tableView:(UITableView*) tableView didSelectRowAtIndexPath:(NSIndexPath*) indexPath
{
std::pair<UITableView*, NSIndexPath*> tableRow(tableView, indexPath);
ObjCTableRowWrapper* oCTableRow = [[[ObjCTableRowWrapper alloc] initWithTableRow:tableRow] autorelease];
[self performSelector:@selector(selectRow:) withObject:oCTableRow];
}

- 101
- 2
- 4
my two cents to be a bit "cleaner":
use typedefs:
typedef NSArray<NSString *> StringArray;
in code we can do:
StringArray * titles = @[@"ID",@"Name", @"TYPE", @"DATE"];

- 10,876
- 3
- 61
- 48
A possible way could be subclassing NSArray but Apple recommends not to do it. It is simpler to think twice of the actual need for a typed NSArray.

- 66,855
- 13
- 106
- 140
-
1It save time to have static type checking at compiling time, editing is even better. Especially helpful when you are writing lib for long term usage. – pinxue May 07 '13 at 16:41