daydreamer
daydreamer

Reputation: 91949

Objective-C: NSArray of Custom Class?

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

Answers (4)

justadev
justadev

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

Dmitry Zhurov
Dmitry Zhurov

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

Mike
Mike

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:

https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-XID_172

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

keeshux
keeshux

Reputation: 599

Sadly there are no generics in Objective-C.

Upvotes: 0

Related Questions