보관물

Posts Tagged ‘OutOfScope’

[cocos2d] schedule사용시 일부 parameter의 out of scope현상

7월 21, 2011 댓글 남기기

Problem

schedule을 사용하여 일정간격으로 특정 fuction(testMethod)를 실행시키려는 도중
testMethod에서 일부 parameter를 정상적으로 참조하지 못하는 문제가 발생.

breakpoint를 찍어 보면 out of scope라고 알려줌.

관련 Source

Foo.h

@interface Foo : CCLayer {

 NSString *pBirdName;
XActionManager *pActionManager;

}
@end

Foo.m

#import “Foo.h”

@implementation Foo {

@synthesize pActionManager;

-(id) init {

…전략…
pBirdName = [NSString stringWithString:@”Peacock”];
pActionManager = [[XActionManager alloc] init];
…후략…

}

-(void) someFunction {

[self schedule:@selector(testMethod) interval:2.0f];

}

-(void) testMethod {

[self unschedule:_cmd];

…중략…
//pBirdName : out of scope
//pActionManager : 정상
[self anotherMethod:pBirdName actionManager:pActionManager];
…중략…

[self schedule:@selector(testMethod) interval:2.0f];

}

}

Cause

anotherMethod에서 pActionManager는 정상적으로 사용이 가능한데 pBirdName은 out of scope가 발생되고 있다.
그래서 의도한 결과가 나오질 않고 있는 상황.
이것은 autorelease와 관련이 있다.
-(id) init 의 실행이 끝나는 순간 pBirdName은 autorelease처리가 되기 때문에 out of scope가 발생된다.
이를 해결하기 위해서는 pBirdName의 retainCount를 증가(eg. [pBirdName retain])시키거나 property를 사용하는 방법이 필요하다.

Solution

pBirdName을 property를 선언하고 self.pBirdName으로 접근하니 정상적으로 동작한다.

Foo.h 에 추가

@property (nonatomic, retain) NSString *pBirdName;

Foo.m에 추가

@synthesize pBirdName;

-(id) init의 pBirdName부분을 수정

self.pBirdName = [NSString stringWithString:@”Peacock”];

-(void) testMethod에서 anotherMethod호출 부분을 수정

[self anotherMethod:self.pBirdName actionManager:pActionManager];

-(void) dealloc에 pBirdName추가

self.pBirdName = nil;

카테고리:cocos2d 태그:, ,