views:

437

answers:

4

Hi everyone! My app involves a user being able to drag specific items such as volume sliders and UIImage views. My goal is to be able to save the locations of the items so that the user can not have to drag the items again after re-launch. Unfortunately, I have seen errors along taking the 'saving CGRect rect = item.frame to NSuserDefaultsorNSKeyedArchiver' route. Any other suggestions?

A: 

You would probably encode CGRect using NSData and then store NSData object using NSUserDefaults or NSKeyedArchiver.

I'm not sure what errors exactly are you referring in your question, maybe more explanation needed?

stefanB
A: 

You have to convert the floats in the CGRect to NSNumbers and then put them in a Dictionary.

If you need to store a lot of CGRects, I recommend creating a little lightweight class with the CGRect elements as archivable NSNumber attributes. Create an initializer that takes a CGRect. Then write quick NSCoder protocol methods so the entire object can be archived

That way you can you quickly and easy convert, store and then retrieve the CGRects.

TechZen
A comment with the down checks would be nice. If nothing else, it lets me know why I am wrong. I took the approach that the `CGRect` needs to be stored as numbers so they can be manipulated as numbers. If you need to actively manage a large set of `CGRect`s, a wrapper class saves a lot of time and effort in the long run.
TechZen
+6  A: 

You could use NSStringFromgCGRect() and CGRectFromString() to store them.

Ben Gottlieb
+1  A: 

If you're using keyed archiving on iPhone, UIKit specifically supports an addition that looks like this: -encodeCGRect:forKey: and does precisely what you want. See the Apple docs for NSCoder's UIKit additions.

If you're using NSUserDefaults, you don't get the luxury of using an explicit encoder for CGRects, but as some other answers say, you could save them as strings using NSStringFromCGRect() and its reverse.

quixoto
Thanks so much!!!
Flafla2