1

我想在一个数组中存储相同的数字 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)
}
4

2 回答 2

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]];
}
于 2012-11-27T14:34:21.590 回答
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”的当前值在它们之间。

于 2012-11-27T14:45:57.420 回答