【iPhone代码片段之七】用NSUserDefaults作为缓存工具 .

本工具仅支持缓存NSString类型数据。


CacheUtil.h,代码如下:

#import <Foundation/Foundation.h>

@interface CacheUtil : NSObject {

}

+(void)cacheItems:(NSString*)item for:(NSString*)key;
+(NSString*)cachedItemsFor:(NSString*)key;
+(void)removeCacheItem:(NSString*)key;

@end




CacheUtil.m,代码如下:
#import "CacheUtil.h"

@implementation CacheUtil

//用键值key,缓存item
+(void)cacheItems:(NSString*)item for:(NSString*)key {
	NSUserDefaults* defaults= [NSUserDefaults standardUserDefaults];
	[defaults setObject:item forKey:key];
}

//取出键值为key的缓存内容
+(NSString*)cachedItemsFor:(NSString*)key {
	NSUserDefaults* defaults= [NSUserDefaults standardUserDefaults];
	NSString* item = [defaults objectForKey:key];
	return item;
}

//删除键值为key的缓存
+(void)removeCacheItem:(NSString*)key {
	NSUserDefaults* defaults= [NSUserDefaults standardUserDefaults];
	[defaults removeObjectForKey:key];
}
						  
@end

你可能感兴趣的:(NSUserDefaults)