【问题标题】:How to use SKSceneDelegate (and abuse)如何使用 SKSceneDelegate(和滥用)
【发布时间】:2015-08-07 09:11:54
【问题描述】:

通常我像往常一样设置我的代表:

@interface CAKGameViewController : UIViewController <CAKGameSceneDelegate>

然后在 CAKGameScene.h 中跟进

@protocol CAKGameSceneDelegate;

@interface CAKGameScene : SKScene <SKPhysicsContactDelegate>
...(properties, etc)
@protocol CAKGameSceneDelegate <NSObject>

@optional
- (void)getStarted;
@end

但正如我们大多数人所知,您必须像这样设置商店:

@property (nonatomic, weak, readwrite) id<CAKGameSceneDelegate> myDelegate;

我的问题是,我想使用实际的 SKSceneDelegate (self.delegate,而不是 (self.myDelegate) 并像这样:

@interface CAKGameViewController : UIViewController <SKSceneDelegate>

现在这很好,我可以使用 self.delegate 来引用控制器,但问题是我似乎无法弄清楚如何自定义 CAKGameViewController,即进一步设置协议,或自定义协议,为我的方法和/或属性。 :(

任何帮助都会有所帮助。

谢谢

【问题讨论】:

标签: ios objective-c cocoa delegates skscene


【解决方案1】:

我终于找到了一个合适的解决方法来使用和分配 SKScene 委托。诀窍是施放(当然是对的)!?

你接口 GameViewController 并遵守协议

在 CAKGameViewController.h 中

@interface CAKGameViewController : UIViewController
<SKSceneDelegate, CAKGameSceneDelegate>

在 CAKGameScene.h 中

@protocol CAKGameSceneDelegate <NSObject>
// any @property;
// or - (void)methods;
@end

在 CAKGameViewController.m 中,您使用 self 分配委托:

self.scene.delegate = self;  //this is the Apple delegate property

然后在你想用的时候

something = self.delegate.property; // <or>
[self.delegate method]; // from the CAKGameSceneDelegate protocol

你投了

something = ((id<CAKGameSceneDelegate>)self.delegate).property; // <or>
[((id<CAKGameSceneDelegate>)self.delegate) method];  // from non-apple protocol

我所做的只是做了一个#define

#define delegateHelper ((id<CAKGameSceneDelegate>)self.delegate)

那么我可以:

something = delegateHelper.property;
[delegateHelper method];

我只是想如果你要拥有一个称为委托的属性,就像大多数 cocoa/objective-c 对象所做的那样,为了让事情正常工作,委托应该是委托,你不应该使用 myDelegate 或其他东西愚蠢的。 delegateHelper 可能不会好很多,但对我来说,我可以接受这种解决方法。

【讨论】:

    【解决方案2】:

    您可以在协议定义中扩展原始委托:

    @protocol CAKGameSceneDelegate <SKSceneDelegate>
        //extend SKSceneDelegate with new functions here
    @end
    

    或者在 Swift 中:

    protocol CAKGameSceneDelegate: SKSceneDelegate
    {
        //extend SKSceneDelegate with new functions here
    }
    

    如果你这样做,你不必重新定义delegate

    【讨论】:

      猜你喜欢
      • 2011-08-14
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      相关资源
      最近更新 更多