0

I use NSDefaults for saving objects.

I want to save an object which contains properties, that point to another object which inherits from NSObject and contains properties like NSString and etc...

How can I do it?

Example:

#import <Foundation/Foundation.h>
#import "user.h"

@interface dataManager : NSObject
@property (strong,nonatomic)user* user;
@end


@interface user : NSObject
@property (copy,nonatomic) NSString* userName;
@property (assign,nonatomic)int age;
@end


I want to save dataManager to NSDefaults and it's properties as well (regardless the number of them).

AnthonyLambert
  • 8,768
  • 4
  • 37
  • 72
  • can't you just use setObject:forKey? – Jbryson Apr 10 '15 at 14:49
  • Your classes will after confirm to `NSCoding` or [`NSSecureCoding`](https://developer.apple.com/library/prerelease/ios//documentation/Foundation/Reference/NSSecureCoding_Protocol_Ref/index.html) and archive your custom object, since [`NSUserDefaults` can only accept certain types](https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html). – Mike D Apr 10 '15 at 14:57

1 Answers1

0

If you want to have it persistent - your objects need to implement NSCoding protocol:

For example for "user" class add those functions, and in header add protocol information

.h

@interface user : NSObject <NSCoding>

.m

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.userName forKey:@"userName"];
    [encoder encodeInt:self.age forKey:@"age"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        self.userName = [decoder decodeObjectForKey:@"userName"];
        self.age = [decoder decodeIntForKey:@"age"];
    }
    return self;
}
Grzegorz Krukowski
  • 18,081
  • 5
  • 50
  • 71