更新:随着新增内容(下标和数字),此问题已过时。
我最近看到一些类子类化NSArray
(或任何集合类)的代码来保存原始值。
这个想法不是写作:
myArray = [NSArray arrayWithObject:[NSNumber numberWithInt:42]];
[[myArray objectAtIndex:0] intValue];
你可以写:
myArray = [NSPrimitiveObjectArray arrayWithObject:42];
[myArray objectAtIndex:0];
我再也找不到这个代码了。有人也会看到它,还记得网址吗?
我也很感激使用它的人的反馈 - 或类似的代码 - 以及他们对此的看法。我在看到这段代码时没有保存链接的原因是我对使用可能会长期带来问题的语言感到厌恶。
答案 0 :(得分:1)
如果我这样做,我可能只是在NSArray和/或NSMutableArray上写一个类别。像这样:
@interface NSMutableArray (PrimitiveAccessors)
- (void)addInteger:(NSInteger)value;
- (NSInteger)integerAtIndex:(NSUInteger)index;
- (void)addFloat:(float)value;
- (float)floatAtIndex:(NSUInteger)index;
// etc...
@end
@implementation NSMutableArray (PrimitiveAccessors)
- (void)addInteger:(NSInteger)value;
{
[self addObject:[NSNumber numberWithInteger:value]];
}
- (NSInteger)integerAtIndex:(NSUInteger)index;
{
id obj = [self objectAtIndex:index];
if (![obj respondsToSelector:@selector(integerValue)]) return 0;
return [obj integerValue];
}
- (void)addFloat:(float)value;
{
[self addObject:[NSNumber numberWithFloat:value]];
}
- (float)floatAtIndex:(NSUInteger)index;
{
id obj = [self objectAtIndex:index];
if (![obj respondsToSelector:@selector(floatValue)]) return 0;
return [obj floatValue];
}
// etc...
@end
但实际上,这似乎更值得工作。在NSNumber中包装原语并将它们拉回原来并不是那么难......