Question

I wrapped NSRects in NSValues to get them into an NSMutableArray. I now want to add saving/loading capabilities to my app, so I thought I'd use NSKeyedArchiver and NSKeyedUnarchiver. Wrong! NSKeyedArchiver cannot archive structs. After a bit of searching I found a forum post from someone with the same problem. He solved it by using NSArchiver and NSUnarchiver. I implemented that, but once again, it didn't work. I can now encode it, but if I decode my array, I get back an array of NSRects! You can't even put them into an array! But I don't care, as long as I can get my rects back. But I can't, because NSArray only has methods for retrieving an object. A struct is not an object, so I can't retrieve my rects. How is this possible? How can I retrieve my archived rects?

Part of MyDocument.m:

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
    NSMutableArray *array = odview.ovals;
    return [NSArchiver archivedDataWithRootObject:array];
}

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
    NSMutableArray *array = [NSUnarchiver unarchiveObjectWithData:data];
    NSMutableArray *newOvals = [NSMutableArray array];
    NSLog(@"array: %@", array);
    NSUInteger i, count = [array count];
    for (i = 0; i < count; i++) {
        NSRect rect = [array objectAtIndex:i];            // I can't do that because a struct is not an object!
        [newOvals addObject:[NSValue valueWithRect:rect]];
    }
    odview.ovals = newOvals;
    return YES  ;
}

How is is possible the wrapping NSValues disappear and how can I safely save and load my NSRects?

Was it helpful?

Solution

I think the easiest way is to use NSStringFromCGRect and CGRectFromString to convert back and forth -- store the rects as strings in your array and then just use writeToFile:atomically: (or writeToURL:atomically:) to save your array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top