开发者

NSKeyedArchiver/NSuserDefaults - saving a CGRect

开发者 https://www.devze.com 2022-12-20 01:53 出处:网络
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 hav

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?


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


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.


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号