我在使目标c中起作用时遇到问题。我有以下协议:
@protocol PFItem <NSObject>
- (NSNumber *)weight;
- (NSNumber *)cost;
@end
该协议在以下类中实现:
@interface PFItemObject : NSObject <NSCoding, PFItem> {
NSString *name;
NSNumber *weight;
NSNumber *cost;
}
@property (retain, nonatomic) NSString *name;
@property (retain, nonatomic) NSNumber *weight;
@property (retain, nonatomic) NSNumber *cost;
@property (readonly) NSString *className;
+ (id)itemWithString:(NSString *)string;
@end
现在,这对我来说很好用,除了当我像这样使用PFItemObject作为超类时:
@interface PFWeaponObject : PFItemObject <NSCoding, PFItem> {
NSString *damage;
NSString *critical;
NSString *range;
NSNumber *attackBonus;
NSNumber *damageBonus;
WeaponTypes type;
BOOL isTwoHanded;
}
@property (retain, nonatomic) NSString *damage;
@property (retain, nonatomic) NSString *critical;
@property (retain, nonatomic) NSString *range;
@property (retain, nonatomic) NSNumber *attackBonus;
@property (retain, nonatomic) NSNumber *damageBonus;
@property WeaponTypes type;
@property BOOL isTwoHanded;
+ (PFWeaponObject *)unarmedWeapon;
@end
+itemWithString:
中的PFWeaponObject
方法是这样的:+ (id)itemWithString:(NSString *)string {
NSArray *components = [string componentsSeparatedByString:@";"];
PFWeaponObject *weapon = [[PFWeaponObject alloc] init];
[weapon setName:[components objectAtIndex:0]];
[weapon setWeight:[NSNumber numberWithFloat:[[components objectAtIndex:1] floatValue]]];
[weapon setCost:[NSNumber numberWithInt:[[components objectAtIndex:2] intValue]]];
[weapon setDamage:[components objectAtIndex:3]];
[weapon setCritical:[components objectAtIndex:4]];
[weapon setRange:[components objectAtIndex:5]];
[weapon setType:[[components objectAtIndex:6] integerValue]];
[weapon setAttackBonus:[NSNumber numberWithInt:[[components objectAtIndex:7] intValue]]];
[weapon setDamageBonus:[NSNumber numberWithInt:[[components objectAtIndex:8] intValue]]];
[weapon setIsTwoHanded:[[components objectAtIndex:9] boolValue]];
return [weapon autorelease];
}
我认为,因为我继承自PFItemObject,所以我应该能够毫无问题地将值分配给超类的属性。但是当我执行以下操作时:
- (void)testItemCreationStrings {
NSString *weaponString = @"+1 Greatsword;25;2500;2d6;x3;Melee;5;1;1;YES";
PFWeaponObject *sampleWeapon = [PFWeaponObject itemWithString:weaponString];
}
超类(
PFItemObject
)中的所有属性都返回@"+1 Greatsword"
。我错过了我应该做的事情吗?感谢您提供的任何帮助,如果需要,请随时询问更多信息。
最佳答案
编辑,因为问题已被编辑。我想我有解决办法。
尝试这个:
+ (id)itemWithString:(NSString *)string {
NSArray *components = [string componentsSeparatedByString:@";"];
PFWeaponObject *weapon = [[PFWeaponObject alloc] init];
[weapon setName:[components objectAtIndex:0]];
[weapon setWeight:[NSNumber numberWithInt:[[components objectAtIndex:1] intValue]]];
[weapon setCost:[NSNumber numberWithInt:[[components objectAtIndex:2] intValue]]];
// etc.
// etc.
}
我认为您未设置NSNumberFormatter的行为和格式,并且我也认为没有必要使用它。如果确实出于某种原因想要使用数字格式化程序,还有其他示例。如果有您想要/需要的理由,我可以提供指导。