常用归档

作者: YvanLiu | 来源:发表于2017-03-27 18:07 被阅读7次
    1).h文件中
    
    #define USER_ID         @"userid"
    #define USER_NAME       @"username"
    #define USER_BIRTHDAY   @"userbirthday"
    #define USER_SEX        @"usersex"
    #define USER_AVATAR     @"useravatar"
    ---------------------
    @property (copy, nonatomic) NSString *userID;
    @property (copy, nonatomic) NSString *userName;
    @property (copy, nonatomic) NSString *userSex;
    @property (copy, nonatomic) NSString *userBirthday;
    @property (copy, nonatomic) NSString *userAvatar;
    ---------------------
    
    /**
     *  归档单例
     *
     *  @return loginManager
     */
    + (instancetype)shareManager;
    
    /**
     *  保存数据
     */
    - (void)saveManager;
    
    2).m文件中
    static YFLoginManager *manager = nil;
    - (instancetype)initWithCoder:(NSCoder *)aDecoder {
        
        if (self = [super init]) {
            self.userID         = [aDecoder decodeObjectForKey:USER_ID];
            self.userName       = [aDecoder decodeObjectForKey:USER_NAME];
            self.userSex        = [aDecoder decodeObjectForKey:USER_SEX];
            self.userBirthday   = [aDecoder decodeObjectForKey:USER_BIRTHDAY];
            self.userAvatar     = [aDecoder decodeObjectForKey:USER_AVATAR];
        }
        return self;
    }
    
    - (void)encodeWithCoder:(NSCoder *)aCoder {
        
        [aCoder encodeObject:self.userID forKey:USER_ID];
        [aCoder encodeObject:self.userName forKey:USER_NAME];
        [aCoder encodeObject:self.userSex forKey:USER_SEX];
        [aCoder encodeObject:self.userAvatar forKey:USER_AVATAR];
        [aCoder encodeObject:self.userBirthday forKey:USER_BIRTHDAY];
        
    }
    
    + (instancetype)shareManager {
        if (!manager) {
            [self read];
            if (!manager) {
                manager = [[self alloc]init];
            }
        }
        return manager;
    }
    
    + (YFLoginManager *)read {
        NSString *filename = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/loginManager.dat"];
        YFLoginManager *loginManager = [NSKeyedUnarchiver unarchiveObjectWithFile:filename];
        return loginManager;
    }
    - (void)saveManager {
        NSString *filename = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/loginManager.dat"];
        [NSKeyedArchiver archiveRootObject:self toFile:filename];
    }
    
    

    相关文章

      网友评论

        本文标题:常用归档

        本文链接:https://www.haomeiwen.com/subject/ofgrottx.html