Assignment #3 Task #10

Please note, this blog entry is from a previous course. You might want to check out the current one.

Once the user picks a scale by pinching or a new origin by panning or tapping, the new value should be stored in NSUserDefaults so that the scale and origin persist as new programs are graphed and even through relaunchings of your program.

When we store the scale in setScale as string:

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    
    [defaults setFloat:self.scale 
                forKey:[NSString stringWithFormat:@"graphViewScale%i", 
    [defaults synchronize];    

and the origin in setOrigin as number array:

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    
    [defaults setObject:
        [NSArray arrayWithObjects:
            [NSNumber numberWithFloat:self.origin.x], 
            [NSNumber numberWithFloat:self.origin.y], 
            forKey:[NSString stringWithFormat:@"graphViewOrigin%i", 
    [defaults synchronize];    

and read those values in setGraphView where we also put some code for when we have no previously stored values:

    CGPoint point;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *defaultOrigin = [defaults arrayForKey:[NSString stringWithFormat:@"graphViewOrigin%i", self.graphView.tag]];    
    if (defaultOrigin) {
        point.x = [[defaultOrigin objectAtIndex:0] floatValue];
        point.y = [[defaultOrigin objectAtIndex:1] floatValue];
    } else {
        point.x = self.graphView.bounds.origin.x + self.graphView.bounds.size.width / 2;
        point.y = self.graphView.bounds.origin.y + self.graphView.bounds.size.height / 2;
    self.origin = point;
    CGFloat defaultScale = [defaults floatForKey:[NSString 
        stringWithFormat:@"graphViewScale%i", self.graphView.tag]];
    if (defaultScale) self.scale = defaultScale;

Leave a Reply

Your email address will not be published.