我有一门课可以帮助我跨会话存储持久数据。问题是我想在整个 Persistance 类的实例中将属性列表或“plist”文件的运行示例存储在 NSMutableArray 中,以便我可以读取和编辑值并在需要时将它们写回。
问题是,由于这些方法是公开定义的,我似乎无法毫无错误地访问声明的 NSMutableDictionary。我在编译时遇到的特定错误是:
warning: 'Persistence' may not respond to '+saveData'
所以在我解决这个问题之前,它会让我的整个过程无法使用。
这是我完整的持久性课程(请注意,它尚未完成,因此只是为了说明这个问题):
持久性.h
#import <UIKit/UIKit.h>
#define kSaveFilename @"saveData.plist"
@interface Persistence : NSObject {
NSMutableDictionary *saveData;
}
@property (nonatomic, retain) NSMutableDictionary *saveData;
+ (NSString *)dataFilePath;
+ (NSDictionary *)getSaveWithCampaign:(NSUInteger)campaign andLevel:(NSUInteger)level;
+ (void)writeSaveWithCampaign:(NSUInteger)campaign andLevel:(NSUInteger)level withData:(NSDictionary *)saveData;
+ (NSString *)makeCampaign:(NSUInteger)campaign andLevelKey:(NSUInteger)level;
@end
持久性.m
#import "Persistence.h"
@implementation Persistence
@synthesize saveData;
+ (NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kSaveFilename];
}
+ (NSDictionary *)getSaveWithCampaign:(NSUInteger)campaign andLevel:(NSUInteger)level
{
NSString *filePath = [self dataFilePath];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSLog(@"File found");
[[self saveData] setDictionary:[[NSDictionary alloc] initWithContentsOfFile:filePath]]; // This is where the warning "warning: 'Persistence' may not respond to '+saveData'" occurs
NSString *campaignAndLevelKey = [self makeCampaign:campaign andLevelKey:level];
NSDictionary *campaignAndLevelData = [[self saveData] objectForKey:campaignAndLevelKey];
return campaignAndLevelData;
}
else
{
return nil;
}
}
+ (void)writeSaveWithCampaign:(NSUInteger)campaign andLevel:(NSUInteger)level withData:(NSDictionary *)saveData
{
NSString *campaignAndLevelKey = [self makeCampaign:campaign andLevelKey:level];
NSDictionary *saveDataWithKey = [[NSDictionary alloc] initWithObjectsAndKeys:saveData, campaignAndLevelKey, nil];
//[campaignAndLevelKey release];
[saveDataWithKey writeToFile:[self dataFilePath] atomically:YES];
}
+ (NSString *)makeCampaign:(NSUInteger)campaign andLevelKey:(NSUInteger)level
{
return [[NSString stringWithFormat:@"%d - ", campaign+1] stringByAppendingString:[NSString stringWithFormat:@"%d", level+1]];
}
@end
我通过在我想要的位置包含头文件来像任何其他类一样调用这个类:
@import "Persistence.h"
然后我像这样调用函数本身:
NSDictionary *tempSaveData = [[NSDictionary alloc] [Persistence getSaveWithCampaign:currentCampaign andLevel:currentLevel]];