Save list of CGPoints using NSUserDefaults
Asked Answered
A

2

18

I have a bunch of CGPoints from a CCTMXLayer I want to save to NSUserDefaults but cannot seem to figure out an elegant way of doing so.

Originally I was hoping to save an NSDictionary with an NSMutableSet for a value containing several NSValues (valueWithCGPoint). From what I can tell neither NSMutableSet or NSValue is supported by NSUserDefaults.

At this point I am considering saving the x&y values of the CGPoint as a string and just converting it back and forth as needed.

Alleras answered 1/1, 2011 at 21:46 Comment(1)
Have you considered just using an NSKeyedArchiver to a file? (Rather than using NSUserDefaults.)Pedicle
T
48

There exists a pair of functions NSStringFromCGPoint and CGPointFromString. You can use these to produce an array of strings representing the points for serialization, and then convert back when you're finished.

Towline answered 1/1, 2011 at 22:10 Comment(1)
Remarkable! I had no idea these functions existed. Always finding out new facets of objective-c.Alleras
E
1

Box them in NSValue objects. Once they're in there, you can write the NSValues out to disk (since they conform to <NSCoding>) or put them in NSUserDefaults or whatever.

Eponym answered 1/1, 2011 at 21:56 Comment(3)
This is exactly my problem. I am trying to store an NSArray (or NSSet...I have tried both) of NSValues using NSUserDefaults but keep receiving an error: [NSUserDefaults setObject:forKey:]: Attempt to insert non-property valueAlleras
Property lists don't use <NSCoding>. NSValue objects cannot be written to plists.Towline
Oh duh, sorry. Yes, you'll have to use an NSKeyedArchiver to convert the NSValues into NSDatas (or an NSArray into an NSData)Eponym

© 2022 - 2024 — McMap. All rights reserved.