【问题标题】:Creating an object, strange question创建一个对象,奇怪的问题
【发布时间】:2011-02-23 21:27:56
【问题描述】:
我有一个“Projectiles”类,我想用它创建一个对象。
为了最小化代码,我想从一个字符串中指定对象,它会清理很多东西。
示例:
我有字符串,
tempenemy.atktype = @"homing_fireball";
现在我想从 Projectiles 类中创建一个同名的对象:
Projectiles *tempenemy.atktype;
这可能吗?所以最终结果将是 Projectiles 类中的一个对象,称为 homing_fireball..?
谢谢!!
【问题讨论】:
标签:
iphone
objective-c
nsstring
cocos2d-iphone
nested
【解决方案1】:
我怀疑这是可能的。但我不是 Objective-c 内核的专家。
我建议您将 Projectile 存储在 NSMutableDictionary 中。您可以使用 @"homing_fireball" 的键存储对象。然后你可以用
之类的东西来引用它
Projectile *someProjectile = [myProjectiles objectForKey:tempenemy.atktype];
【解决方案2】:
如果我明白你的意思,你是在尝试以 atktype 作为其成员来初始化一个射弹对象吗?你调用 main..
Projectiles* tempProjectiles = [[Projectiles alloc]initWithType:@"homing_fireball"];
你的射弹.h
// blah blah blah
{
NSString* atktype;
}
@property (nonatomic, retain)NSString* atktype;
-(id)initWithType:(NSString*)type;
你的射弹.m
@synthesize atktype;
-(id)initWithType:(NSString*)type
{
self = [super init];
if(self)
{
atktype = type;
}
return self;
}