Challenge, Chap 18


In doing this challenge I borrowed heavily from project built in the chapter, but I stored my various rectangles, after converting them to NSValue objects in a mutable array. I then, in the draw method, do a fast enumeration on the array, convert back to the rectangle and then redraw all items each time I add one. Although not terribly efficient, it does show the various ovals on the display. So that part is working. Now I was feeling ambitious and wanted to save the array of objects out.

This is where I am stumbling, I think that what I need to use is encodeArrayOfObjCType:count:at: method but I am not sure of the first and last arguments. I am fairly certain that count: would be the count of items in the array, but I don’t know how to specify the Type or what at: refers to. The more I read in the documentation, the more confused I got. Since the array is not keyed, I am at a loss here.


You can archive your array of NSValues like this:

And then unarchive it:

I can’t tell for sure, but I think that this is newly possible in the 10.7 SDK, and that older versions didn’t actually implement encoding rects, even from within an NSValue.

An alternative is to use NSStringFromRect() and NSRectFromString(). All are in NSGeometry.h.



Hi !

Everything works fine except from the saving part.

I implemented the following methods in myDocument.m.

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
	NSData * data = [NSKeyedArchiver archivedDataWithRootObject:ovals];
	return data;

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
	ovals = [NSKeyedUnarchiver unarchiveObjectWithData:data];
	[ovalView setNeedsDisplay:YES];
    return YES;

ovals is an NSMuttableArray of NSValue *. The NSValue are built with NSRect.

When I want to save my awesome oval drawing, I choose the name and the directory of the file and nothing happens.
I get the following console Log :

Exception detected while handling key input.
2012-01-07 13:49:06.582 OvalShop[28972:a0f] *** -[NSKeyedArchiver encodeValueOfObjCType:at:]: this archiver cannot encode structs
2012-01-07 13:49:06.582 OvalShop[28972:a0f] *** -[NSKeyedArchiver dealloc]: warning: NSKeyedArchiver deallocated without having had -finishEncoding called on it.

I don’t understand why it doesn’t work. I do not see what I’m missing.
Thank you.

I’m on Mac OS 10.6.8 with Xcode 3.2.6.
Please sorry for my bad english, I’m French.



The issue is that the Mac OS X 10.6 SDK doesn’t support archiving NSValues containing NSRect/NSPoint/NSSize/etc (this appears to have been added in 10.7). Instead, you will need to convert those values to some other value which you can archive. I would suggest using NSStringFromRect()/NSRectFromString() to transform the oval rect values as appropriate.