NSUserdefaults用法总结

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

UserInfoManager.h文件

#import <UIKit/UIKit.h>


@interface UserInfoManager : NSObject

+(BOOL)initWithDic:(NSDictionary *)dic;

+(NSDictionary *)readUserInfo;

+(BOOL)isFirstLoad;

+(BOOL)updateWithObject:(id)obj forKey:(NSString *)key;

+(BOOL)updateWithBool:(BOOL)boolValue forKey:(NSString *)key;

+(BOOL)updateWithFloat:(float)floatValue forKey:(NSString *)key;

@end

UserInfoManager.m文件

#import "UserInfoManager.h"

#import "Foundation/Foundation.h"


@interface UserInfoManager ()


@end


@implementation UserInfoManager


//是否第一次登陆

+(BOOL)isFirstLoad

{

    if([[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstLoad"])

    {

        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isFirstLoad"];

        return YES;

    }


    else

    {

        return NO;

    }

}

//创建一个NSUserDefaults对象用以保存数据

+(BOOL)initWithDic:(NSDictionary *)dic

{

    NSUserDefaults * userInfoManager = [NSUserDefaults standardUserDefaults];

    if (dic == Nil) {

        return NO;

    }

    NSArray * keys = [dic allKeys];

    for(int i = 0;i < [keys count];i ++)

    {

        [userInfoManager setObject:[dic objectForKey:[keys objectAtIndex:i]] forKey:[keys objectAtIndex:i]];

    }

    return [userInfoManager synchronize];

}


//读取数据

+(NSDictionary *)readUserInfo

{

   NSUserDefaults * userInfoManager = [NSUserDefaults standardUserDefaults];  

   return [userInfoManager dictionaryRepresentation];

}


//更改某项数据

+(BOOL)updateWithObject:(id)obj forKey:(NSString *)key

{

    [[NSUserDefaults standardUserDefaults] setObject:obj forKey:key];

   return  [[NSUserDefaults standardUserDefaults] synchronize];

}


+(BOOL)updateWithBool:(BOOL)boolValue forKey:(NSString *)key

{

    [[NSUserDefaults standardUserDefaults] setBool:boolValue  forKey:key];

    return  [[NSUserDefaults standardUserDefaults] synchronize];

}


+(BOOL)updateWithFloat:(float)floatValue forKey:(NSString *)key

{

    [[NSUserDefaults standardUserDefaults] setFloat:floatValue  forKey:key];

    return  [[NSUserDefaults standardUserDefaults] synchronize];

}

@end