情景設定:父層HelloWorldLayer有一個方法-(void) setlable;需要被其子層SecondLayer訪問。
第一種、半單例方法:
首先在HelloWorldLayer.h聲明+(HelloWorldLayer*) shareLayer
- +(HelloWorldLayer*) shareLayer;
然後在HelloWorldLayer.m加入:
- #import "SecondLayer.h"
-
- static HelloWorldLayer* HelloWorldLayerInstance;
-
- +(HelloWorldLayer*) shareLayer
- {
- return HelloWorldLayerInstance;
- }
-
- -(id) init
- {
- // always call "super" init
- // Apple recommends to re-assign "self" with the "super" return value
- if( (self=[super init])) {
- HelloWorldLayerInstance=self;
-
- SecondLayer* sl=[[SecondLayer alloc] init];
- sl.tag=10;
- [self addChild:sl z:100];
- self.isTouchEnabled=YES;
-
- ////.................
-
- }
- return self;
- }
-
- -(void) setlable
- {
- clickNum++;
- [label setString:[NSString stringWithFormat:@"ParentLayer clickNum:%i",clickNum]];
- }
在SecondLayer就可以通過這樣的方式來訪問HelloWorldLayer的-(void) setlable方法:
- [[HelloWorldLayer shareLayer] setlable];
第二種、self.parent強制訪問方法:
HelloWorldLayer中只需按正常添加子層SecondLayer即可(HelloWorldLayer.m中):
- -(id) init
- {
- // always call "super" init
- // Apple recommends to re-assign "self" with the "super" return value
- if( (self=[super initWithColor:ccc4(0, 255, 255,255)])) {
- HelloWorldLayerInstance=self;
-
- SecondLayer* sl=[[SecondLayer alloc] init];
- sl.tag=10;
- [self addChild:sl z:100];
- self.isTouchEnabled=YES;
-
- ////.................
-
- }
- return self;
- }
在SecondLayer就可以通過這樣的方式來訪問HelloWorldLayer的-(void) setlable方法:
- [(HelloWorldLayer*)self.parent setlable];
第三種、協議委托方法:
在SecondLayer.h中加入:
- #import <Foundation/Foundation.h>
- #import "cocos2d.h"
-
- @protocol callParentDelegate <NSObject>
- -(void) setlable;
- @end
-
- @interface SecondLayer : CCLayer{
- id<callParentDelegate> delegate;
- }
- @property(nonatomic,retain) id<callParentDelegate> delegate;
- @end
SecondLayer.m中@synthesize delegate;
然後在HelloWorldLayer.h中加入<callParentDelegate>協議:
- @interface HelloWorldLayer :CCLayer <callParentDelegate>
- {
- CCLabelTTF *label;
- int clickNum;
- }
在HelloWorldLayer.m中實現:
- -(void) setlable
- {
- clickNum++;
- [label setString:[NSString stringWithFormat:@"ParentLayer clickNum:%i",clickNum]];
- }
在添加SecondLayer子層注意設子委托:
- SecondLayer* sl=[[SecondLayer alloc] init];
- sl.tag=10;
- sl.delegate=self;
- [self addChild:sl z:100];
- self.isTouchEnabled=YES;
在SecondLayer就可以通過這樣的方式來訪問HelloWorldLayer的-(void) setlable方法:
- [self.delegate setlable];
還有更好的辦法,歡迎各位交流!