暂时在iOS

时间:2016-01-04 12:27:18

标签: nsuserdefaults

我有暂时保存对象的问题。我有一个应用程序,取决于api 100%。因此,除了一些用户默认设置之外,我不需要保存任何内容。但是现在我需要临时保存一些对象以在结帐页面中显示它们。

这里的问题是我无法将整个对象保存在NSUserdefaults中,因为它只接受通用值。

有没有办法在不使用CoreData的情况下保存我的对象?

1 个答案:

答案 0 :(得分:0)

您可以将对象保存在NSUserDefaults中, 创建一个对象的NSObject类,如下面的代码中的User.h,

@interface User : NSObject

@property (nonatomic, strong) NSString *userId;
@property (nonatomic, strong) NSString *userName;

+ (void)saveCustomObject:(User *)object key:(NSString *)key;
+ (User *)loadCustomObjectWithKey:(NSString *)key;
@end

在User.m文件中

- (void)encodeWithCoder:(NSCoder *)encoder
{
   //Encode properties, other class variables, etc
   [encoder encodeObject:self.userId forKey:@"UserID"];
   [encoder encodeObject:self.userName forKey:@"UserName"];
}

- (id)initWithCoder:(NSCoder *)decoder
{
  if(self = [super init])
  {
      //decode properties, other class vars
      self.userId = [decoder decodeObjectForKey:@"UserID"];
      self.userName = [decoder decodeObjectForKey:@"UserName"];
   }
  return self;
}

//encoding the DataModel
+ (void)saveCustomObject:(User *)object key:(NSString *)key
{
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [UserDefaults setObject:encodedObject forKey:key];
    [UserDefaults synchronize];
}

+ (User *)loadCustomObjectWithKey:(NSString *)key
{
    NSData *encodedObject = [UserDefaults objectForKey:key];
    User *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
}

保存数据

User *dataObj = [User new];
dataObj.userId = //User value userid;
dataObj.userFirstName = //user value for user name
//Save user data in UserDefaults
[User saveCustomObject:dataObj key:@"UserData"];

和反向用户数据,

User *userObj = [User loadCustomObjectWithKey:@"UserData"];