1

我在游戏中有一个经常使用的类,我认为通过将实例变量与 typedef 结构组合在一起来整理它会很好。我并不完全相信这是否会有所帮助。

最初在我的类头接口中,我有这样的东西:

@interface ThingClass : CCLayer {

     @public

          bool _invulnerableToggled;
          int _invulnerableCount;
          int _invulnerableMax;

}

@property(nonatomic, assign) bool invulnerableToggled;
@property(nonatomic, assign) int invulnerableCount;
@property(nonatomic, assign) int invulnerableMax;

在我的.m

@synthesize

invulnerableToggled = _invulnerableToggled,
invulnerableCount = _invulnerableCount,
invulnerableMax = _invulnerableMax;

此类的子类会将这些变量设置为它们在 init 中的默认值。另一个类可以访问该子类的实例并使用常规点符号相应地设置值,例如 tempThing.invulnerableToggled = YES;

现在我使用的是 typedef 结构,看起来好像我的值无法调整,我已经尝试了各种方法来克服它。虽然这可能是因为我一开始就没有正确设置,所以以防万一我会告诉你我现在在做什么。

目前我的班级标题:

typedef struct {

    bool toggled;
    int count;
    int max;

} Invulnerable;

@interface ThingClass : CCLayer {

     @public
          Invulnerable _invulnerable;

}

@property(nonatomic, assign) Invulnerable invulnerable;

在我的.m

@synthesize

invulnerable = _invulnerable;

我在子类 init 中设置这些值,如下所示:

_invulnerable.toggled = NO;
_invulnerable.count = 0;
_invulnerable.max = 50;

当我尝试在另一个类中设置它时,我希望它将 1 添加到当前值。它始终保持为 1。这个 if 语句有时每秒检查 60 次,但计数没有改变:

Invulnerable invulnerable = tempBaddy.invulnerable;

// check baddy invulnerability and increment if needed

if(invulnerable.toggled == YES){

    int increase = invulnerable.count +1;

    invulnerable.count = increase;

    NSLog(@"invulnerable.count = %i", invulnerable.count);
}
4

1 回答 1

0

This is not a common way in ObjC but you can pass the struct by reference, i.e. return a pointer to the struct:

@interface ThingClass : CCLayer {
@protected
    Invulnerable _invulnerable;
}

@property(nonatomic, readonly) Invulnerable* invulnerable;

@end

The *.m file:

@implementation ThingClass

- (Invulnerable*)invulnerable {
    return &_invulnerable;
}

@end

Updating the data:

Invulnerable* invulnerable = tempBaddy.invulnerable;
// check baddy invulnerability and increment if needed
if(invulnerable->toggled == YES){
    invulnerable->count++;
    NSLog(@"invulnerable.count == %i", tempBaddy.invulnerable->count);
}

I guess you are trying to perform some action on an instance of ThingClass (or its subclass). And the action affects the value of _invulnerable. In this case a more common way would be having a method in the Thing class that performs all the required updates:

@implementation ThingClass

- (void)headshot {
    if (_invulnerable.toggled) {
        _invulnerable.count++;

    } else {
        [self die];
    }
}

@end
于 2013-06-09T16:50:27.207 回答