1

更新:随着新增内容(下标和数字),这个问题已经过时了。


我最近看到了一些类子类NSArray(或任何集合类)的代码来保存原始值。

这个想法不是写:

myArray = [NSArray arrayWithObject:[NSNumber numberWithInt:42]];
[[myArray objectAtIndex:0] intValue];

你可以写:

myArray = [NSPrimitiveObjectArray arrayWithObject:42];
[myArray objectAtIndex:0];

我再也找不到这个代码了。会有人看到它,并记住网址吗?

我也会感谢使用过它的人(或类似代码)的反馈以及他们对它的看法。看到这段代码时我没有保存链接的原因是我有一种用这种语言进行黑客攻击的感觉,这可能会带来长期的问题。

4

1 回答 1

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 中包装原语并将它们拉回来并不难......

于 2012-01-03T16:17:20.310 回答