最佳的方式来初始化变化的对象 [英] Optimal way to initialize varying objects
本文介绍了最佳的方式来初始化变化的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要初始化很多不同类型的基于整数参数的对象的。它们都具有相同的总体初始化方法。
I have to initialize a lot of different types of objects based on an integer parameter. They all have the same overall initialization methods.
目前,我有以下的code
At the moment I have the following code
#def APPLE 1
#def PEAR 2
switch (t)
{
case APPLE:
newobj = [[FApple alloc] init];
break;
case PEAR:
newobj = [[FPear] alloc] init];
break;
default:
retobj = nil;
}
我相信一定会有更好的方式来做到这一点。当我添加FOrange我必须去这里添加另一行。
I believe there must be a better way to do this. When I add FOrange I have to go and add another line here.
这将是一个更好的办法?
What would be a better way?
推荐答案
您需要一个映射的数字 - >键入的地方,但你并不需要重复code:
You need a mapping number -> type somewhere, but you don't need to repeat the code:
NSDictionary* d = [NSDictionary dictionaryWithObjectsAndKeys:
[FPear class], [NSNumber numberWithInt:PEAR ],
[FApple class], [NSNumber numberWithInt:APPLE],
nil];
Class c = [d objectForKey:[NSNumber numberWithInt:t]];
id x = [[c alloc] init];
这篇关于最佳的方式来初始化变化的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文