There is a class with two fields of type NSString . How to save several (alternately, that is, more than once) of its objects in NSUserDefaults ?


UPD:

Will it be correct to read an array from a key, add an object to it, and then rewrite the key?

    1 answer 1

    The array will not work, NSUserDefaults can save only NSData, NSString, NSNumber, NSDate + dictionaries and arrays of them, and of course simple types like int.

    You can save your class in general form into an array by packing it into NSData via [NSKeyedArchiver archivedDataWithRootObject:myObject]; , in your class there should be a method - (void)encodeWithCoder:(NSCoder *)encoder , respectively there are pair methods for unpacking.

    But specifically in your case, it seems to me easier to throw a class into the dictionary:

     NSDictionary dictionary=[NSDictionary dictionaryWithObjectsAndKeys:myObj.field1,@"field1", myObj.field2,@"field2",nil]; 

    and already these dictionaries pack into an array

    • @aknew, NSUserDefaults has a “ setObject ” method, and any array will be an object. - Niki-Timofe 1:53 pm
    • Well, if you know about this method, you can read its description in the help: The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. Property list objects - aknew 1:57 pm For NSArray and NSDictionary objects
    • > But specifically in your case, it seems to me easier to throw a class into the dictionary. In what sense? -----> Note that dictionaries in property lists must also contain only property values. - Niki-Timofe
    • Corrected the answer, I proceed from the fact that the NSString fields as you described, in fact this is the same archiving - aknew