【发布时间】:2012-03-28 14:06:51
【问题描述】:
我在目标 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"。我是否错过了一些我应该做的事情?
感谢您提供的任何帮助,如果您需要,请随时询问更多信息。
【问题讨论】:
-
你真的在你的真实代码中覆盖了 name 属性吗?即 [weapon setName: [...]] 连续调用 3 次。
-
不,我只是复制/粘贴不正确。我已经在我的问题中更正了它。
-
您可能想发布真实代码。推测是类方法声明和实例方法定义不匹配,代价为“objectAtIndex:0”。
-
好的,所以我通过直接从 Xcode 复制/粘贴代码来更新它。这正是现在正在运行的。
-
如何合成/定义属性方法?
标签: objective-c ios inheritance protocols