如何初始化数组中的所有位置?

时间:2012-11-27 14:24:47

标签: objective-c ios6

我想将相同的数字存储在数组中100次。这些数字稍后会改变,但我想用一个计数器写一个if语句,最初填充所有100个插槽,值为0.有没有一种简单的方法可以做到这一点?

喜欢这个,其中'block01'需要更改为'block02','block03'等:

int block01 = 0;

NSMutableDictionary* myDict = [[NSMutableDictionary alloc] init];

if(myDict)
{
    [myDict setObject:block01 forKey:@"block01stored"];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [paths objectAtIndex:0];
    NSString *path = [documentPath stringByAppendingPathComponent:@"blocks.save"];

    BOOL successfulWrite = [myDict writeToFile: path atomically: YES];
    if(successfulWrite == NO)
}

2 个答案:

答案 0 :(得分:0)

您可以创建NSNumber(这是一个对象,但int不是),然后将其存储到NSMutableDictionary中:

NSNumber* num = [NSNumber numberWithInt:0];

for (int i = 1; i<=100; i++) {
   [myDict setObject:num forKey:[NSString stringWithFormat:@"block%dstored",i]];
}

答案 1 :(得分:0)

这应该对你有所帮助。这是一个循环,将执行99次(1 - 100),将零作为对象格式化为包含当前数字的对象。

NSMutableDictionary* myDict = [[NSMutableDictionary alloc] init];
for (int i = 1; i <= 100; i ++) {
    if(myDict)
    {
        [myDict setObject:[NSNumber numberWithInt:0] forKey:[NSString stringWithFormat:@"block%.3istored",i]];
    }
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *path = [documentPath stringByAppendingPathComponent:@"blocks.save"];
BOOL successfulWrite = [myDict writeToFile: path atomically: YES];
if(successfulWrite == NO)

编辑:要获取某个密钥的值,您可以使用以下内容:

int myInt = [[myDict objectForKey:@"block050stored"] intValue];

如果您想要替换某个键的对象,它就像以下一样简单:

[myDict setObject:[NSNumber numberWithInt:1] forKey:@"block020stored"];

现在,%.3i告诉字符串添加一个数字(i),格式化为总是三位数。 (000,001,010,099,100)

[NSString stringWithFormat:@"block%.3istored",i]

所以上面的行基本上意味着,创建一个带有“block”和“stored”字样的字符串,其中包含int“i”的当前值在它们之间的三位数表示。