1

假设我有这些方法:

+(CCSprite *)a {
    return [self shapeFromRect:CGRectMake(0, 224, 224, 288) rotate:0];
}

+(CCSprite *)b {
    return [self shapeFromRect:CGRectMake(0, 224, 224, 288) rotate:0];
}

+(CCSprite *)c {
    return [self shapeFromRect:CGRectMake(0, 100, 50, 50) rotate:0];
}

+(CCSprite *)d {
    return [self shapeFromRect:CGRectMake(0, 100, 50, 50) rotate:90];
}

有冗余,所以我可以像这样重构它:

+(CCSprite *)a {
    return [self shapeFromRect:[self abRect] rotate:0];
}

+(CCSprite *)b {
    return [self shapeFromRect:[self abRect] rotate:0];
}

+(CCSprite *)c {
    return [self shapeFromRect:[self cdRect] rotate:0];
}

+(CCSprite *)d {
    return [self shapeFromRect:[self cdRect] rotate:90];
}

+(CGRect)abRect {
    return CGRectMake(0, 224, 224, 288);
}

+(CGRect)cdRect {
    return CGRectMake(0, 100, 50, 50);
}

但我想知道,有没有更有效的方法来做到这一点?

有没有办法可以将这些 CGRects 存储在 typedef 枚举或其他形式的常量中,这样我就不必执行方法调用?

4

1 回答 1

2
+ (CCSprite *)sprite:(NSInteger)type
{
    float r = (type == 3)? 90 : 0;
    if (type < 2) {
        return [self shapeFromRect:CGRectMake(0, 224, 224, 288)] rotate:r];
    } else {
        return [self shapeFromRect:CGRectMake(0, 100, 50, 50)] rotate:r];
    }
}

也许类似的东西?

于 2012-08-20T19:03:33.840 回答