Archiving data.

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

  1. macrumors member

    Joined:
    Mar 18, 2008
    #1
    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. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    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. thread starter macrumors member

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

    Joined:
    Feb 27, 2006
    Location:
    Kent, United Kingdom
    #4
    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:

    Code:
    @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:

    Code:
    - (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. thread starter macrumors member

    Joined:
    Mar 18, 2008
    #5
    Okay thanks a lot!
     

Share This Page