从文件中加载nsnumber数组并使它们可变



我考虑的一种方法是创建一个临时数组并将NSNumbers的数组加载到其中,然后分配可变数组,然后如果加载的数组不是nil或空addObject:[NSNumber numberWithInt:[[temparr objectAtIndex:i] intValue]],,但它似乎是这样一个迂回的方式。

这样我就可以修改应用程序中的数字和数组内容。

是否有一种更短、更切中要害的方法来做同样的事情?从某处加载数组/字典只是为了发现它们的内容不可变是很常见的,我想学习最直接的方法。

不能使NSNumber对象可变,它们是设计上不可变的对象。

如果你想对数组做一个可变的深层拷贝,也就是说,一个数组的可变拷贝和一个数组内容的可变拷贝(如果可能的话;例如,在NSNumber(您不能)的情况下,您可以这样做:

@interface NSArray (MutableCopyDeep)
- (NSMutableArray *) mutableCopyDeep;
@end
@implementation NSArray (MutableCopyDeep)
- (NSMutableArray *) mutableCopyDeep {
    NSMutableArray *returnAry = [[NSMutableArray alloc] initWithCapacity:[self count]];
    for (id anObject in self) {
        id aCopy = nil;
        if ([anObject respondsToSelector:@selector(mutableCopyDeep)]) {
            aCopy = [anObject mutableCopyDeep];
        } else if ([anObject respondsToSelector:@selector(mutableCopyWithZone:)]) {
            aCopy = [anObject mutableCopy];
        } else if([anObject respondsToSelector:@selector(copyWithZone:)]) {
            aCopy = [anObject copy];
        } else {
            aCopy = [anObject retain];
        }
        [returnAry addObject:aCopy]; 
        [aCopy release];
    }
    // Method name prefixed with "mutableCopy" indicates that the returned
    // object is owned by the caller as per the Memory Management Rules.
    return returnAry;
} 
@end

你不能把nsnumber放在一个可变数组中,并期望能够改变它们的值。关于我使用的解决方法,请参阅问题中的代码。

最新更新