有没有强制在 NSArray、 NSMutableArray 等上键入的方法?

我是否可以创建一个 NSMutableArray实例,其中 所有的元素类型为 SomeClass

43191 次浏览

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.

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.

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?

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

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.

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.

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

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.

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];
}

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"];

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;