ChatGPT解决这个技术问题 Extra ChatGPT

Are there strongly-typed collections in Objective-C?

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?

Just starting to learn about ObjC myself. Perhaps you can use ObjC++ to do the heavy lifting?
You may be interested in answers to this question: Is there any way to enforce typing on NSArray, NSMutableArray, etc.?. Arguments are given why it is not common practice in Objective-C/Cocoa.
ObjC++ isn't really a language... just more of a way to reference ObjC's ability to handle C++ inline just the same as it would handle C. You shouldn't do this unless you have to, though (such as if you need to use a third-party library that was written in C++).
Pretty much an exact duplicate of stackoverflow.com/questions/649483/…
@ Mark W - "shouldn't do this" why not? I've used ObjC++ and it works great. I can do #import and @property std::map myDict; I can use the full Cocoa api AND have strongly-typed collections. I don't see any down-side.

C
Connor

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


Since I have question about generics and types returned in methods I asked my question in different thread, to keep everything clear: stackoverflow.com/questions/30828076/…
@rizzes. Yes, it was just introduced.
One caveat here is that Swift doesn't entirely ignore the type annotations in your generic ObjC class. If you specify constraints, e.g. MyClass <Foo: id<Bar>>, your Swift code will assume values are the type of your constraint, which gives you something to work with. However, specialized subclasses of MyClass would have their specialized types ignored (be seen effectively the same as a generic MyClass). See github.com/bgerstle/LightweightGenericsExample
So does this compile for 10.10, 10.9 and earlier operating systems?
It should as long as you set your deployment target to support them
A
Aaron Brager

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.


I disagree to "don't worry, just send messages to those objects". If you put the wrong type of objects into the collection, which do not respond to these messages, this will yield runtime errors. Using generics in other languages avoids this problem with compile time checks.
@henning77 Yes, but Objective-C is a more dynamic language than these languages. If you want strong type-safety, use those languages.
I also disagree to the don't worry philosophy - for example if you pull the first item out of an NSArray and cast it to an NSNumber but that item was really an NSString, you are screwed...
@RaffiKhatchadourian -- not much choice if you're writing an iOS app. If it was simple to write one with Java, and get all the benefits of writing a native app, believe me: I would.
The biggest complain I have about this isn't to do with dynamic languages vs. compile time checking, but simple developer communication. I can't just look at a property declaration and know what type of objects it is going to return unless it's documented somewhere.
M
Mark Rhodes

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 = ...

I guess this is a good way to have it documented, in case someone else reads your code. Anyway the variable's name should be as clear as possible to know what objects it contains.
K
Kevin

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.


M
Matthew Vines

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.


Link to doc in answer is dead - "Sorry, that page cannot be found".
u
user1259710

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


w
w-m

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.


D
David Jeske

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.


h
htzfun

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.

https://i.stack.imgur.com/UkE24.png


d
drekka

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.


C
Chris Reid

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