dasj
dasj

Reputation: 11

Objective C : Generic containing a scalar?

Xcode seems to allow this:

@interface Foo<__covariant ObjectType> : NSObject
@property  (nonatomic,assign) ObjectType ooo;
@end

However it gives an error for this:

Foo<int> *arrg;

How can I create a class whose generic class is a scalar? I need this.

Upvotes: 0

Views: 248

Answers (1)

dandan78
dandan78

Reputation: 13894

int is a C type, which cannot be directly represented by Objective-C reference types.

Off the top of my head, you could get around this by using NSNumber, which is essentially a very light-weight Objective-C wrapper around numeric types such as int or float.

Alternatively, you could use C++ templates and mix those with Objective-C. I don't know exactly how this works and what kind of restrictions you are likely to encounter, but since Objective-C++ is a thing, I would imagine that this is something it could be used for.

And indeed it looks like it can: this blog post provides an intro to Objective-C++. It turns out you can have C++ ivars in your objc classes, for instance.

Upvotes: 3

Related Questions