问题描述
在学习OOP时,我正在创建一个iPhone应用程序。我有两个名为GUTimer和GUInterval的类。每个实例需要存档到一个plist并在需要时单独取消存档。
我的问题是,我应该创建一个管理类来管理这两个对象类型的加载和保存。还是应该创建单独的类,一个用于管理GUTimer实例的保存和加载以及管理保存和加载GUInterval实例的类?
我还在学习OOP,这是针对我的分级项目,所以我只想提出最好的解决方案。任何帮助将不胜感激。
THanks。
I'm creating an iPhone app while learning OOP. I have two classes named GUTimer and GUInterval. Instances of each need to be archived to a plist and unarchived separately when needed.My question is, should I create one manager class that manages the loading and saving of both these objects types. Or should I create separate classes, one that manages the saving and loading of GUTimer instances and one that manages the saving and loading of GUInterval instances?I'm still studying OOP and this is for my graded project so I just want to come up with the best solution possible. Any help would be appreciated.THanks.
推荐答案
我会让你的对象实现NSCoding协议,然后使用这样的东西来归档/取消存档他们:
I would have your objects implement the NSCoding protocol and then use something like this to archive/unarchive them:
+ (NSObject *)readArchiveFile:(NSString *)inFileName
{
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectoryPath, inFileName];
NSObject *returnObject = nil;
if( [fileMgr fileExistsAtPath:filePath] )
{
returnObject = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
return returnObject;
}
+ (void)archiveFile:(NSString *)inFileName inObject:(NSObject *)inObject
{
NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectoryPath, inFileName];
BOOL didSucceed = [NSKeyedArchiver archiveRootObject:inObject toFile:filePath];
if( !didSucceed )
{
NSLog(@"File %@ write operation %@", inFileName, didSucceed ? @"success" : @"error" );
}
}
+ (void)deleteFile:(NSString *)inFileName
{
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectoryPath, inFileName];
NSError *error;
if ( [fileMgr fileExistsAtPath:filePath] && [fileMgr removeItemAtPath:filePath error:&error] != YES)
{
NSLog(@"Unable to delete file: %@", [error localizedDescription]);
}
}
这篇关于从文件创建一组对象的独立类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!