Archiving data.

Discussion in 'Mac Programming' started by MDMstudios, Mar 19, 2008.

  1. MDMstudios macrumors member

    Mar 18, 2008
    I made a small application in XCode, just trying to get some of the basics of Cocoa and Objective-C, now one of the things that I want to do with my app is make it so it can save value's of some NSTextFields. I have tried learning how to work a archiver, but I don't quite understand the concept of it. So I was wondering if any of you could help me out with it. Thanks!
  2. kainjow Moderator emeritus


    Jun 15, 2000
    Well if they're preferences/settings, you can use NSUserDefaults.

    NSArchiver and related classes are more useful for saving instances of a class. For just plain text fields, you could just put the values into an NSDictionary and write the dictionary to file.

    Or you could write the stringValues of the text fields to file directly.

    There are several ways to do this, but if you give more specifics I can recommend the best approach :)
  3. MDMstudios thread starter macrumors member

    Mar 18, 2008
    What I want to do is archive to string values of two NSTextFields.
  4. stadidas macrumors regular

    Feb 27, 2006
    Kent, United Kingdom
    You will need to make your object be able to archive itself. To do this, edit the header file to tell it to implement the NSCoding interface like this:

    @interface MyObject : NSObject <NSCoding>
    You will then need to implement two methods; one to archive the data, and one to read the archive and restore the data from it. These are as follows:

    - (void)encodeWithCoder:(NSCoder *)coder
        [coder encodeObject:[textField1 stringValue] forKey:@"textField1Value"];
        [coder encodeObject:[textField2 stringValue] forKey:@"textField2Value"];
    - (id)initWithCoder:(NSCoder *)coder
        [textField1 setStringValue:[coder decodeObjectForKey:@"textField1Value"]];
        [textField2 setStringValue:[coder decodeObjectForKey:@"textField2Value"]];
  5. MDMstudios thread starter macrumors member

    Mar 18, 2008
    Okay thanks a lot!

Share This Page