Are there strongly-typed collections in Objective-C?

Objective CGenericsData StructuresCollectionsStrong Typing

Objective C Problem Overview


I'm new to Mac/iPhone programming and Objective-C. In C# and Java we have "generics", collection classes whose members can only be of the type declared. For example, in C#

Dictionary<int, MyCustomObject>

can only contain keys that are integers and values that are of type MyCustomObject. Does a similar mechanism exist in Objective-C?

Objective C Solutions


Solution 1 - Objective C

In Xcode 7, Apple has introduced 'Lightweight Generics' to Objective-C. In Objective-C, they will generate compiler warnings if there is a type mismatch.

NSArray<NSString*>* arr = @[@"str"];
    
NSString* string = [arr objectAtIndex:0];
NSNumber* number = [arr objectAtIndex:0]; // Warning: Incompatible pointer types initializing 'NSNumber *' with an expression of type 'NSString *'

And in Swift code, they will produce a compiler error:

var str: String = arr[0]
var num: Int = arr[0] //Error 'String' is not convertible to 'Int'

Lightweight Generics are intended to be used with NSArray, NSDictionary and NSSet, but you can also add them to your own classes:

@interface GenericsTest<__covariant T> : NSObject

-(void)genericMethod:(T)object;

@end

@implementation GenericsTest

-(void)genericMethod:(id)object {}

@end

Objective-C will behave like it did before with compiler warnings.

GenericsTest<NSString*>* test = [GenericsTest new];
    
[test genericMethod:@"string"];
[test genericMethod:@1]; // Warning: Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'

but Swift will ignore the Generic information completely. (No longer true in Swift 3+.)

var test = GenericsTest<String>() //Error: Cannot specialize non-generic type 'GenericsTest'

> Aside from than these Foundation collection classes, Objective-C lightweight generics are ignored by Swift. Any other types using lightweight generics are imported into Swift as if they were unparameterized.

Interacting with Objective-C APIs

Solution 2 - Objective C

> This answer is outdated but remains for historical value. As of Xcode 7, Connor's answer from Jun 8 '15 is more accurate.


No, there are no generics in Objective-C unless you want to use C++ templates in your own custom collection classes (which I strongly discourage).

Objective-C has dynamic typing as a feature, which means that the runtime doesn't care about the type of an object since all objects can receive messages. When you add an object to a built-in collection, they are just treated as if they were type id. But don't worry, just send messages to those objects like normal; it will work fine (unless of course one or more of the objects in the collection don't respond to the message you are sending).

Generics are needed in languages such as Java and C# because they are strong, statically typed languages. Totally different ballgame than Objective-C's dynamic typing feature.

Solution 3 - Objective C

No, but to make it clearer you can comment it with the type of object you want to store, I've seen this done a few times when you need to write something in Java 1.4 nowadays) e.g.:

NSMutableArray* /*<TypeA>*/ arrayName = ....

or

NSDictionary* /*<TypeA, TypeB>*/ dictionaryName = ...

Solution 4 - Objective C

This was released in Xcode 7 (finally!)

Note that in Objective C code, it's just a compile-time check; there will be no run-time error just for putting the wrong type into a collection or assigning to a typed property.

Declare:

@interface FooClass <T> : NSObject
@property (nonatomic) T prop;
@end

Use:

FooClass<NSString *> *foo = [[FooClass alloc] init];
NSArray<FooClass<NSString *> *> *fooAry = [NSArray array];

Be careful about those *s.

Solution 5 - Objective C

There are no generics in Objective-C.

From the Docs

> Arrays are ordered collections of objects. Cocoa provides several array classes, NSArray, NSMutableArray (a subclass of NSArray), and NSPointerArray.

Solution 6 - Objective C

Apple has added generics to ObjC in XCode 7:

@property NSArray<NSDate *>* dates;
- (NSArray<NSDate *> *)datesBeforeDate:(NSDate *)date;
- (void)addDatesParsedFromTimestamps:(NSArray<NSString *> *)timestamps;

see here: https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html#//apple_ref/doc/uid/TP40014216-CH6-ID61

Solution 7 - Objective C

Generic NSArrays can be realized by subclassing NSArray, and redefining all provided methods with more restrictive ones. For example,

- (id)objectAtIndex:(NSUInteger)index

would have to be redefined in

@interface NSStringArray : NSArray

as

- (NSString *)objectAtIndex:(NSUInteger)index

for an NSArray to contain only NSStrings.

The created subclass can be used as a drop-in replacement and brings many useful features: compiler warnings, property access, better code creation and -completion in Xcode. All these are compile-time features, there is no need to redefine the actual implementation - NSArray's methods can still be used.

It's possible to automate this and boil it down to only two statements, which brings it close to languages that support generics. I've created an automation with WMGenericCollection, where templates are provided as C Preprocessor Macros.

After importing the header file containing the macro, you can create a generic NSArray with two statements: one for the interface and one for the implementation. You only need to provide the data type you want to store and names for your subclasses. WMGenericCollection provides such templates for NSArray, NSDictionary and NSSet, as well as their mutable counterparts.

An example: List<int> could be realized by a custom class called NumberArray, which is created with the following statement:

WMGENERICARRAY_INTERFACE(NSNumber *, // type of the value class
                         // generated class names
                         NumberArray, MutableNumberArray)

Once you've created NumberArray, you can use it everywhere in your project. It lacks the syntax of <int>, but you can choose your own naming scheme to label these as classes as templates.

Solution 8 - Objective C

Take a look at:

https://github.com/tomersh/Objective-C-Generics

It appears to be a sort of poor-man's generics, by repurposing the protocol checking mechanism.

Solution 9 - Objective C

Now dreams come true - there are Generics in Objective-C since today (thanks, WWDC). It's not a joke - on official page of Swift:

> New syntax features let you write more expressive code while improving consistency across the language. The SDKs have employed new Objective-C features such as generics and nullability annotation to make Swift code even cleaner and safer. Here is just a sampling of Swift 2.0 enhancements.

And image that proofs this:Objective-C generics

Solution 10 - Objective C

Just want to jump in here. I've written a blog post over here about Generics.

The thing I want to contribute is that Generics can be added to any class, not just the collection classes as Apple indicates.

I've successfully added then to a variety of classes as they work exactly the same as Apple's collections do. ie. compile time checking, code completion, enabling the removal of casts, etc.

Enjoy.

Solution 11 - Objective C

The Collections classes provided by Apple and GNUStep frameworks are semi-generic in that they assume that they are given objects, some that are sortable and some that respond to certain messages. For primitives like floats, ints, etc, all the C arrays structure is intact and can be used, and there are special wrapper objects for them for use in the general collection classes (eg NSNumber). In addition, a Collection class may be sub-classed (or specifically modified via categories) to accept objects of any type, but you have to write all the type-handling code yourself. Messages may be sent to any object but should return null if it is inappropriate for the object, or the message should be forwarded to an appropriate object. True type errors should be caught at compile-time, not at run-time. At run-time they should be handled or ignored. Finally, Objc provides run-time reflection facilities to handle tricky cases and message response, specific type, and services can be checked on an object before it is sent a message or put into an inappropriate collection. Beware that disparate libraries and frameworks adopt different conventions as to how their objects behave when sent messages they do not have code responses for, so RTFM. Other than toy programs and debugging builds, most programs should not have to crash unless they really screw up and try to write bad data to memory or disk, perform illegal operations (eg divide by zero, but you can catch that too), or access off-limits system resources. The dynamism and run-time of Objective-C allows for things to fail gracefully and should be built in to your code. (HINT) if yo are having trouble with genericity in your functions, try some specificity. Write the functions over with specific types and let the runtime select (thats why they are called selectors!) the appropriate member-function at run-time.

Example:
    -(id) sort (id) obj;  // too generic. catches all.
     // better
    -(id) sort: (EasilySortableCollection*) esc;
    -(id) sort: (HardToSortCollection*) hsc; 
    ...
    [Sorter  sort: MyEasyColl];
    [Sorter  sort: MyHardColl];

  

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichView Question on Stackoverflow
Solution 1 - Objective CConnorView Answer on Stackoverflow
Solution 2 - Objective CMarc WView Answer on Stackoverflow
Solution 3 - Objective CMark RhodesView Answer on Stackoverflow
Solution 4 - Objective CKevinView Answer on Stackoverflow
Solution 5 - Objective CMatthew VinesView Answer on Stackoverflow
Solution 6 - Objective Cuser1259710View Answer on Stackoverflow
Solution 7 - Objective Cw-mView Answer on Stackoverflow
Solution 8 - Objective CDavid JeskeView Answer on Stackoverflow
Solution 9 - Objective ChtzfunView Answer on Stackoverflow
Solution 10 - Objective CdrekkaView Answer on Stackoverflow
Solution 11 - Objective CChris ReidView Answer on Stackoverflow