Objective-C中的“泛型”做一个RangeValidator?

时间:2012-03-23 07:51:16

标签: objective-c

在C#中,我可以这样做:

class RangeValidator<T> {
    public T MinValue { get; set; }
    public T MaxValue { get; set; }
}

其中T可以是任何原始类型; intfloatdouble ...或任何“对象”类型; StringDateTime等。

如果在Obj-C中,我是这样做的:

@interface RangeValidator {
    id minValue;
    id maxValue;
}
@property ...

它可以用于说一个NSNumber或NSString,但如果我将一个NSInteger分配给minValue,我会得到像

这样的东西
warning: initialization makes pointer from integer without a cast
// Since an id is a pointer to an object, not an integer. Correct?

这里显而易见的解决方案可能是使用NSNumber。如果有任何其他解决方案可以解决这类问题,我只是好奇吗?

谢谢!

3 个答案:

答案 0 :(得分:2)

正确的方法是使用NSNumber并使用

从整数初始化
[NSNumber numberWithInt:someInt];

这样,该类不需要泛型,您可以通过检查minValuemaxValue是否可以轻松执行验证。理解intValue(或某些比较选择器可能,取决于你想做什么)。

if([minValue respondsToSelector:@selector(intValue)]) {
    return [minValue intValue];
} else {
    ....
}

答案 1 :(得分:2)

如果你想在Objective C中使用泛型,我建议你使用支持C ++模板的Objective C ++而不是这个丑陋的无类型代码。

上面的代码不起作用,因为NSInteger是适当原始类型的typedef而不是指针类型。您应该使用NSNumber包装器。

答案 2 :(得分:1)

我认为惯用的Objective-C解决方案正是您的建议,使用id类型并在NSNumber中包装原始数字值。康斯坦丁提到的NSInteger是一种原始类型 - 请参阅Foundation Data Type Reference

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
#else
typedef int NSInteger;
#endif

原始类型和对象之间的这种不一致有点不幸,您必须学会识别非NSIntegerCGRectCMTime等非对象类型。

相关问题