Reputation: 91949
I am trying to learn iOS
, I come from Java
background where we can have lists/arrays of specific classes like
List<String> l = new ArrayList<>();
List<MyClass> l = new ArrayList<>();
Looking at Objective-C
, I can make use of NSArray
class to make immutable
arrays, but how do I specify that this NSArrray
is strictly of type MyClass
?
Upvotes: 0
Views: 5180
Reputation: 1
You can use NSArray<MyClass*> *myClassArray
to declare an array of MyClass. If you want to make one of your own, you can do something like this.
// The only limitation is that MyGenericType must be an object.
// Exclude __covariant if you are doing something with the same interface in
// a different part of your code
@interface MyGenericClass<__covariant MyGenericType> : NSObject
// Your code here
@end
This usage of __covariant
can be found in the interface for NSArray
and more.
This is how it is used in the NSArray interface.
@interface NSArray<__covariant ObjectType> : NSObject <NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration>
// the code
@end
// A different part of the code using the same interface, so __covariant is excluded.
@interface NSArray<ObjectType> (NSExtendedArray)
// more code
@end
The reason that MyGenericType
must be an object is because Objective C doesn't have an any type, so you use id
in the implementation instead. But numbers can be expressed using NSNumber
. You may also specify multiple __covariants
, just separate them with a comma.
Or you could look into swift.
Upvotes: 0
Reputation: 49
Now Xcode 7 supports some kind of generics for standard collections(e.g. NSArrays). So you can make an array and provide kind of storing objects like this:
NSArray<NSString*> *myArrayOfStrings;
Upvotes: 4
Reputation: 9835
As far as I know, there isn't a built-in mechanism for specifying the type of objects put into NSArrays in Objective-C, but it looks like Swift does what you're looking for if that helps at all:
On a slightly related note, there's a decent write-up here about enforcing inserting objects of only a certain type into a subclassed NSMutableArray and throwing exceptions if trying to insert the wrong object types:
NSMutableArray - force the array to hold specific object type only
Upvotes: 2