我来自 Actionscript 背景。在 Actionscript 中,Class Method 只能访问 Class Methods 和 Class 属性。
但在目标 C 中,
Class方法gameResultAll如何访问Instance方法initFromPlist
+(NSMutableArray *)gameResultAll://Class Method -(id)initFromPlist:(id)plist;//Instance Method NSMutableArray *gameResults = [GameResult gameResultAll]; // (returns GameResult array)
为什么调用 [self init] 方法而不是 [super init] 来从类方法创建实例。
提前致谢。
#import "GameResult.h"
@implementation GameResult
#define GAME_RESULT_KEY @"gameresult_key"
#define SCORE_KEY @"score"
+(NSMutableArray *)gameResultAll
{
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
for (id plist in [[[[NSUserDefaults standardUserDefaults] dictionaryForKey:GAME_RESULT_KEY] mutableCopy] allValues])
{
GameResult *gameResult = [[GameResult alloc] initFromPlist:plist];
[resultArray addObject:gameResult];
}
return resultArray;
}
//Designated initialiser
-(id)initFromPlist:(id)plist
{
self = [self init];
if(self)
{
if([plist isKindOfClass:[NSDictionary class]])
{
NSDictionary *resultDictionary = (NSDictionary*)plist;
_score = (int)resultDictionary[SCORE_KEY];
}
}
return self;
}