UserDefaults - NSMutibleArray循环

时间:2014-04-21 13:57:21

标签: objective-c

Mutible数组包含双打

当前保存的array添加了新doubles,然后重新保存。

NSUserDefaults *defaultDefects = [NSUserDefaults standardUserDefaults];

NSMutableArray *loadDefects = [defaultDefects objectForKey:@"defaultDefects"];

[loadDefects addObject:[NSNumber numberWithDouble:self.defectPositionX ]];
[loadDefects addObject:[NSNumber numberWithDouble:self.defectPositionY ]];

[defaultDefects setObject:loadDefects forKey:@"defaultDefects"];

然后加载它们我需要这个

NSUserDefaults *defaultDefects = [NSUserDefaults standardUserDefaults];
NSMutableArray *loadDefects = [defaultDefects objectForKey:@"defaultDefects"];

//in here I need a foreach loop so it would be something like

double defectX = 0;
double defectY = 0;
int keyValue;    

foreach (loadDefects as key => value) {
    double defectX = [[loadDefects objectAtIndex:keyValue] doubleValue];
    keyValue++;
    double defectY = [[loadDefects objectAtIndex:keyValue] doubleValue];
    keyValue++;
    CGContextMoveToPoint(context, defectX, defectY);
}

我已经用编程方式写了这篇文章,而不是用Objective-C编写它的正确方法,因为这是我想要弄明白的东西。希望你能看到我所做的事情。我试图实现。

1 个答案:

答案 0 :(得分:1)

根据我的理解,您需要使用步骤“2”进行for循环,以便在一个循环步骤中检索XY。试试这个:

for (int i = 0; i < loadDefects.count; i += 2) {
    double defectX = [loadDefects[i] doubleValue];
    double defectY = [loadDefects[i+1] doubleValue];
    CGContextMoveToPoint(context, defectX, defectY);
}

另外,请不要忘记在首次启动应用时初始化loadDefects数组并保存NSUserDefaults中的更改:

NSMutableArray *loadDefects = [defaultDefects objectForKey:@"defaultDefects"];
if (loadDefects == nil) {
    loadDefects = [NSMutableArray array];
}
// ...
// Add elements to array and store it defaultDefects here
// ...
[defaultDefects synchronize];