jasu's blog
블로그 메뉴검색결과 리스트
Programming/ActionScript 3.0에 해당되는 글 106건
- 2007.06.15 [AS3] 비디오의 조작 1
- 2007.06.15 [AS3] SimpleButton 오브젝트의 조작
- 2007.06.15 [AS3] 비트 맵의 작성과 조작
- 2007.06.15 [AS3] 무비 클립의 제어
- 2007.06.15 [AS3] 컨텐츠의 동적 로드 - Loader 클래스 8
- 2007.06.15 [AS3] 텍스트의 조작
- 2007.06.15 [AS3] 벡터 그래픽의 묘화
- 2007.06.15 [AS3] 표시 리스트를 사용하는 어프로치의 이점
- 2007.06.15 [AS3] 정적 프롭퍼티와 스코프 체인
- 2007.06.15 [AS3] Bound methods
- 2007.06.15 [AS3] 파일 내에 복수 클래스
- 2007.06.15 [AS3] for each..in 문법
- 2007.06.15 [AS3] Object 형의 독립
- 2007.06.13 [AS3] Understanding garbage collection in Flash Player 9
- 2007.06.13 [AS3] ActionScript 3 Tip of the Day
- 2007.06.13 [AS3] ActionScript 3.0 첫 프로그래밍 1
글
[AS3] 비디오의 조작
다음은 넷스트림을 비디오에 관련 짓고, 비디오를 Sprite 표시 오브젝트 컨테이너에 추가하는 단순한 예를 보여준다.
글
[AS3] SimpleButton 오브젝트의 조작
upState
downState
overState
이것들은 SimpleButton 오브젝트의 프롭퍼티로 각각 DisplayObject 오브젝트이다. 예를 들어, 다음의 클래스는 단순한 텍스트 버튼을 정의한다.
SimpleButton 오브젝트의 hitTestState 프롭퍼티는 버튼의 마우스 이벤트에 응답하는 DisplayObject 인스턴스다. 이 예의 TextButton 클래스는 버튼 상태 ( 업, 다운, 또는 오버) 에 사용한다. DisplayObject를 정의하는 다음의 클래스를 참조.
글
[AS3] 비트 맵의 작성과 조작
BitmapData 오브젝트는 픽셀의 구형 배열을 나타낸다. 새로운 비트맵을 프로그램 처리에 의해서 작성할 수 있다. 다음의 예는 BitmapData constructor을 사용하여 지정한 색으로 구형을 작성할 수 있고 그 BitmapData 오브젝트를 새로운 Bitmap 오브젝트에 할당할 수 있는 것을 보여준다.
그러나 통상은 로드된 이미지 파일의 비트맵 데이터를 조작하기 위해 사용된다. 어느 경우도BitmapData 클래스에는 BitmapData를 조작해 변경하기 위한 메소드가 포함된다. 예를 들어, setPixel() 메소드를 사용하여 픽셀의 특정의 RGB 값으로 설정할 수 있다.
글
[AS3] 무비 클립의 제어
ActionScript 1.0 및 2.0 의 MovieClip 클래스의 프롭퍼티 및 메소드의 상당수는 ActionScript 3.0의 MovieClip 클래스의 프롭퍼티 및 메소드를 제공되고 있다. 그 일부는 슈퍼 클래스로부터 계승된다. 예를 들어 DisplayObject 클래스의 x ,y , 및 blendMode 등의 프롭퍼티는 MovieClip 클래스에서 계승되기 때문에 사용할 수 있다. AS3의 MovieClip 클래스는 DisplayObject 클래스를 확장하기 때문이다. _x ,_y ,_root 등의 언더스코아 문자로 시작되는 이름의 프롭퍼티는 ActionScript 3.0 에서 언더 스코아 문자가 없는 이름으로 변경되었다. 또 _xmouse, _xscale, _ymouse , 및 _yscale 프롭퍼티의 이름은, mouseX ,scaleX ,mouseY , 및 scaleY로 변경되었다.
MovieClip 클래스에는 무비 클립을 제어하기 위한 메소드와 프롭퍼티가 포함된다. 그러한 프롭퍼티를 사용하면 무비 클립의 프레임과 씬의 총수, 및 현재의 재생 헤드 위치에 있는 프레임과 씬에 관한 정보를 감시할 수 있다. (currentFrame ,currentLabel ,currentLabels ,currentScene ,scenes , 및 totalFrames) 아래의 메소드를 사용하면 무비 클립의 재생 헤드를 제어할 수 있다. gotoAndPlay() ,gotoAndStop() ,nextFrame() ,nextScene() ,play() ,prevFrame() ,prevScene() , 및 stop()
예를 들어, 다음의 코드는 myMovie MovieClip 오브젝트의 현재의 씬의 선두 프레임에 재생 헤드를 이동한다.
myMovie.gotoAndPlay(0);
Stage 오브젝트의 frameRate 프롭퍼티를 사용하면 어플리케이션내의 모든 무비 클립의 frame rate를 설정할 수 있다. (Stage.frameRate = 30;)
ActionScript 1.0 및 2.0 과는 달리 ActionScript 3.0에서는 로드된 SWF파일은 MovieClip 오브젝트, AVM1Movie 오브젝트, 또는 Sprite 오브젝트로 사용할 수 있으나 ActionScript 3.0의 MovieClip 오브젝트의 타임 라인만을 제어할 수 있다. Sprite 및 AVM1Movie 오브젝트에는 타임 라인 관련의 메소드 및 프롭퍼티는 포함되지 않는다.
글
[AS3] 컨텐츠의 동적 로드 - Loader 클래스
Loader 오브젝트를 사용하여 어플리케이션에 SWF 파일 및 그래픽 파일을 로드 할 수 있다. Loader 클래스는 DisplayObjectContainer 클래스의 서브 클래스이므로 Loader 오브젝트에는 표시 리스트 표시 오브젝트를 사용할 수 있다. SWF 파일 또는 그래픽 파일을 나타내는 표시 오브젝트는 Loader로 작성된 인스턴스 1개당 1 개만 포함할 수 있다. 표시 리스트에 Loader 오브젝트를 추가할 때는 다음의 코드와 같이 표시 오브젝트의 로드가 완료하면 로드 된 표시 오브젝트도 표시 리스트에 추가해야 화면에서 확인이 가능하다
SWF 파일 또는 이미지가 로드 되면 로드 된 표시 오브젝트를 아래 코드처럼 container DisplayObjectContainer 오브젝트등의 다른 표시 오브젝트 컨테이너로 이동할 수 있다
LoaderInfo 클래스
파일이 로드 되면 LoaderInfo 오브젝트가 작성된다. 이 오브젝트는 Loader 오브젝트 및 로드 된 표시 오브젝트 양쪽 모두의 프롭퍼티다. 즉, LoaderInfo 오브젝트는 Loader 오브젝트의 contentLoaderInfo 프롭퍼티를 경유하는 Loader 오브젝트의 프롭퍼티이며 또, 표시 오브젝트의 loaderInfo 프롭퍼티도 로드된 표시 오브젝트의 프롭퍼티이다. 로드 된 표시 오브젝트의 loaderInfo 프롭퍼티는 Loader 오브젝트의 contentLoaderInfo 프롭퍼티와 같다. 즉, LoaderInfo 오브젝트는 로드 된 오브젝트와 로드하는 Loader 오브젝트간 ( 로드 되는 측과 로드하는 측) 공유하게 된다.
LoaderInfo 클래스는 로드의 진행 상황 로드하는 측과 로드 되는 측의 URL 미디어의 총바이트수, 미디어의 규격, 높이와 폭등의 정보를 제공한다. LoaderInfo 오브젝트는 로드의 진행 상황을 감시하기 위한 이벤트를 송출한다.
로드 된 컨텐츠의 프롭퍼티에 액세스 하려면 다음의 코드와 같이 LoaderInfo 오브젝트에 이벤트 청취자를 추가해야 한다.
LoaderContext 클래스
Loader 클래스의 load() 또는 loadBytes() 메소드를 사용해 Flash Player 에 외부 파일을 로드하는 경우, context 파라미터를 지정할 수도 있다. 이 파라미터는 LoaderContext 오브젝트이다.
LoaderContext 클래스에는 로드 된 컨텐츠의 사용 방법의 문맥을 정의할 수 있는 다음과 같은 프롭퍼티가 포함되어 있다.
checkPolicyFile-- 이미지 파일을 로드하는 경우에게만 이 프롭퍼티를 사용한다. 이 프롭퍼티를 true로 설정하면 Loader 에 의해서 오리지날 서버로 크로스 도메인 폴리시 파일의 유무가 체크된다. 이것은 Loader 오브젝트를 포함하는 SWF가 있는 도메인 이외의 다른 도메인에 있는 컨텐츠를 로드할 경우에만 사용된다. 서버로부터 Loader 도메인에 액세스 허가가 주어지고 있는 경우라면 Loader 도메인 내의 SWF 파일의 ActionScript는 로드 된 이미지내의 데이터에 액세스 할 수 있다. 즉, BitmapData.draw() 커멘드를 사용하여 로드 된 이미지내의 데이터에 액세스 할 수 있다.
Loader 오브젝트의 도메인 이외의 다른 도메인에 SWF가 있을 경우에 Security.allowDomain()을 호출해 특정의 도메인을 허가할 수가 있다.
securityDomain - SWF 파일을 로드하는 경우에게만 이 프롭퍼티를 사용한다. Loader 오브젝트를 포함한 파일이 있는 도메인 이외의 도메인에 있는 SWF 파일에 대해서 이 프롭퍼티를 지정한다.이 옵션을 지정하면 Flash Player는 크로스 도메인 폴리시 파일이 존재할지를 체크하게 된다. 파일이 존재하는 경우는 크로스 도메인 폴리시 파일로 허가되고 있는 도메인의 SWF 파일은 로드된 SWF 컨텐츠를 크로스 스크립트 할 수 있다. 이 파라미터로서 flash.system.SecurityDomain.currentDomain을 지정할 수 있다.
다음은 다른 도메인으로부터 비트 맵을 로드할 때, 크로스 도메인 폴리시 파일의 유무를 체크하는 예를 나타낸다.
다음은 SWF 파일을 Loader 오브젝트와 같은 시큐러티 샌드 박스에 두기 위해서 다른 도메인으로부터 SWF 파일을 로드할 때 크로스 도메인 폴리시 파일의 유무를 체크하는 예를 나타낸다. 또, 이 코드는 로드된 SWF 파일의 클래스를 Loader 오브젝트와 같은 어플리케이션 도메인에 추가한다.
글
[AS3] 텍스트의 조작
다음의 예에 나타나듯이 TextFormat 오브젝트를 사용하여 TextField 전체 또는 임의의 범위의 텍스트의 포맷을 설정할 수 있다.
Text 필드에는 plaintext 또는 HTML 형식의 텍스트의 어느쪽이든 포함할 수 있다. plaintext는 인스턴스의 text 프롭퍼티에 포함되어 HTML 텍스트는 htmlText 프롭퍼티에 포함된다.
다음 예와 같이 StyleSheet 오브젝트를 사용해 CSS 스타일 시트를 HTML 텍스트에 적용할 수 있다.
글
[AS3] 벡터 그래픽의 묘화
예를 들어, 다음의 코드는 Shape 오브젝트로 오렌지를 묘화 한다.
Graphics 클래스에는 단순한 셰이프를 간단하게 묘화하기 위한 다음의 메소드가 포함되어있다.
drawCircle()
drawEllipse()
drawRect()
drawRoundRect()
drawRoundRectComplex()
묘화 메소드를 호출하기 전에
linestyle()
lineGradientStyle()
beginFill()
beginGradientFill()
beginBitmapFill() 메소드를 호출하고 선스타일, fills, 또는 그 양쪽 모두를 정의하게 된다.
( 다른 표시 오브젝트를 포함한다) 표시 오브젝트 컨테이너이기도 하면서 타임 라인을 필요로 하지 않는 그래피컬 오브젝트를 작성하는 경우는 Sprite 클래스를 사용한다.
예를 들어, 다음의 Sprite 오브젝트에는 graphics 프롭퍼티로 묘화 한 circle의 아이 리스트내에 TextField 오브젝트가 있다.
Sprite 또는 MovieClip 오브젝트의 그래픽 층은 항상 Sprite 또는 MovieClip의 아이 표시 오브젝트의 배후에 표시되지만 그래픽 층은 Sprite 또는 MovieClip의 아이 리스트에는 표시되지 않는다.
글
[AS3] 표시 리스트를 사용하는 어프로치의 이점
ActionScript 1.0 및 2.0에서는 MovieClip 오브젝트에서만 셰이프를 표현할 수 있었다. 하지만 ActionScript 3.0 에서는 셰이프를 표현 할 수 있는 간단한 표시 오브젝트 클래스가 있다. ActionScript 3.0 표시 오브젝트 클래스에는 MovieClip 오브젝트에 포함되는 메소드와 프롭퍼티가 모두 포함되지 않기 때문에 기존의 ActionScript(2.0 이하)보다 메모리 및 프로세서 자원에의 부담이 경감되었다.
예를 들어, 각 MovieClip 오브젝트에는 무비 클립의 타임 라인의 프롭퍼티가 포함됩니다만 Shape 오브젝트에는 포함되지 않는다. 타임 라인을 제어하기 위한 프롭퍼티는 대량의 메모리 및 프로세서 자원을 사용하는 경우가 있지만 ActionScript 3.0의 Shape 오브젝트를 사용하면 퍼포먼스가 향상된다. Shape 오브젝트는 복잡한 MovieClip 오브젝트보다 오버헤드가 적기 때문이다. Flash Player가 Shape에서는 MovieClip 프롭퍼티를 관리할 필요는 없기 때문에 스피드가 향상과 함께 오브젝트가 사용하는 메모리 용량을 줄일 수 있어 전제적으로는 CPU의 낭비를 줄일 수 있는 이점이 생겼다.
심도 관리의 향상
ActionScript 1.0 및 2.0에서의 depths는 직선적인 심도 관리 및 getNextHighestDepth() 등의 메소드를 사용해 관리되고 있었다. ActionScript 3.0에서는 표시 오브젝트의 심도를 관리하기 위해서 편리한 메소드 및 프롭퍼티가 포함된다. DisplayObjectContainer 클래스가 바로 그것이다.
ActionScript 3.0는 표시 오브젝트를 DisplayObjectContainer 인스턴스의 아이 리스트 내의 새로운 위치로 이동하면 표시 오브젝트 컨테이너 내의 다른 아이는 자동적으로 위치가 변경되어 표시 오브젝트 컨테이너내의 적절한 아이 인덱스 위치를 할당할 수 있다.
ActionScript 3.0는 항상 표시 오브젝트 컨테이너의 아이 오브젝트를 모두 찾아낼 수 있다. 어느 DisplayObjectContainer 인스턴스에도 표시 오브젝트 컨테이너의 아이의 수를 일람표시 할 수 있는 numChildren 프롭퍼티를 제공하고 있다. 또 표시 오브젝트 컨테이너의 아이 리스트는 항상 인덱스 리스트이기 위해 리스트내의 인덱스 위치 0으로부터 마지막 인덱스 위치 (numChildren - 1) 까지의 모든 오브젝트를 조사할 수 있다. 이것은 ActionScript 1.0 및 2.0 의 MovieClip 오브젝트의 메소드와 프롭퍼티에서는 불가능했던 점이다.
ActionScript 3.0는 표시 리스트 내를 순서로 이동하는 것은 간단하다. 왜냐하면 표시 오브젝트 컨테이너의 아이 리스트의 인덱스 번호에 결핍 번호가 없기 때문이다. 표시 리스트 내의 이동과 오브젝트의 depths 관리는 ActionScript 1.0 및 2.0 보다 간단하게 되었다. ActionScript 1.0 및 2.0에서는 무비 클립의 심도순서에 불연속인 결핍이 있는 오브젝트가 포함되어 있었기 때문에 오브젝트의 리스트 내를 이동하는 것이 곤란했지만 ActionScript 3.0에서는 표시 오브젝트 컨테이너의 각각의 아이 리스트가 1 개의 배열로서 내부에 캐쉬되므로 인덱스에 의한 룩업이 매우 고속으로 실행된다. 또한 표시 오브젝트 컨테이너의 모든 아이를 매우 고속으로 루프 할 수도 있게 되었다.
표시 리스트내의 자유로운 이동
ActionScript 1.0 및 2.0 에서는 벡터 셰이프나 Flash authoring tool로 묘화 된 오브젝트에는 액세스 할 수 없다. ActionScript 3.0에서는 그러한 표시 리스트상의 모든 오브젝트, 즉 ActionScript를 사용해 작성된 오브젝트 및 Flash authoring tool로 작성된 모든 표시 오브젝트에 액세스 할 수 있게 되었다.
글
[AS3] 정적 프롭퍼티와 스코프 체인
인스턴스 프롭퍼티가 같은 클래스 또는 슈퍼 클래스내에서 정적 프롭퍼티와 같은 이름을 사용하고 있는 경우 인스턴스 프롭퍼티는 스코프 체인내에서 우선 순위가 높아진다. 이는 정적 프롭퍼티의 값이 아니라 인스턴스 프롭퍼티의 값이 사용되는 것을 의미한다.
다른 예로 parent_mc라는 무비클립에 포함된 child_mc라는 무비클립이 있을 때 두개의 무비클립에 CLICK 이벤트 적용하게 되면 결과는 아래와 같이 나오게 된다.
parentClickHandler에서 해당 이벤트가 적용된 무비클립에 접근하기 위해서는 아래와 같은 형태로 접근을 시도해야 한다.
글
[AS3] Bound methods
출력 :
[object global]
foo's this:[object ThisTest]
num: 3
Bound methods foo() 의 this 참조가 그 직전의 행의 this 참조가 글로벌 오브젝트를 가리키고 있지만 여전히 ThisTest 클래스의 인스턴스를 가리키는 것을 나타내고 있다. 게다가 myFunc 변수에 속하고 있는 Bound methods는 계속 ThisTest 클래스의 멤버 변수에 액세스 할 수 있다. 이 같은 코드를 ActionScript 2.0에서 실행하면 this 참조가 일치하기 때문에 num 변수는 undefined 가 된다.
글
[AS3] 파일 내에 복수 클래스
하지만 ActionScript 3.0 에서는 1개의 파일 내에 복수의 클래스를 저장할 수 있도록 설계되었다. Flash 9 alpha 버전에서는 package{} 내에서도 internal class로 여러 개의 클래스가 package내에서 사용가능하도록 하였으나 CS3로 만들면서 이러한 기능은 제외되었다. 하지만 package 외에는 여러개의 클래스를 정의할 수가 있도록 되어 있다. 1 개의 원시 소스 파일에 복수의 클래스를 보존하는 것이 편리할 수도 있지만 남용하면 OOP형태의 언어에서 바람직하지 않은 문제를 양산할 우려가 있다. 문제는 다음과 같은 경우이다.
1. 복수의 클래스가 1 개의 소스파일에 보존되고 있는 경우, 각각의 클래스를 재이용하는 것이 곤란하게 된다.
2. 파일명과 클래스명이 대응하고 있지 않는 경우, 특정의 클래스의 원시 소스코드를 찾아내는 것이 곤란하다.
이러한 문제점으로 인하여 Adobe에서는 각각 하나의 클래스는 하나의 원시소스파일로 저장하는 것을 권장하고 있다. Alpha 버전에서 package 내에서 복수 클래스를 정의할 수 있었던 것을 제외시킨 이유 또한 이러한 문제점 때문일 것이라는 생각이다.
다시 생각해보면 기존 ActionScript 2.0에서 디렉토리 형태로만 패키지 영역을 정의했던 것을 벗어나 package에서 명시적으로 패키지 영역을 정의하고 그 영역 안에서 복수의 클래스를 정의할 수 있도록 하는 방향으로 검토하였으나 위와 같은 두가지 문제로 인하여 언어적 비판을 벗어나기 위해 CS3 제품에서 package 내 복수 클래스 정의 부분을 제외한 것이 아닌가 생각된다. 개념적 접근에서 실의[實義]를 추구했다고 보여진다.
글
[AS3] for each..in 문법
for each (var num in myObj) {
trace (num);
}
//
출력 :
// 20
// 30
XML 또는 XMLList 오브젝트의 반복 처리를 실행.
var myXML:XML = <users>
<fname>Jane</fname>
<fname>Susan</fname>
<fname>John</fname>
</users>;
for each (var item in myXML.fname) {
trace(item);
}
/*
출력
Jane
Susan
John
*/
배열의 엘리먼트의 반복 처리를 실행할 수도 있음.
var myArray:Array = ["one", "two", "three"];
for each (var item in myArray) {
trace (item);
}
//
출력 :
// one
// two
// three
글
[AS3] Object 형의 독립
1. var obj:Object;
2. var obj;
하지만 ActionScript 3.0에서는 형을 지정되어 있지 않은 변수라고 하는 개념이 도입되었다. 이는 다음의 1, 2번과 같이 2 개의 방법으로 지정할 수 있다.
1. var obj:*;
2. var obj;
3. var obj:Object;
형이 지정되어 있지 않은 1번과 2번은 3번의 Object 형태의 변수와 같지는 않다. 주된 차이는 형이 지정되어 있지 않은 변수는 특별한 값 undefined 를 담을 수 있지만 Object 형태의 변수는 그 값을 보관 유지할 수 없다는 것이다. 오직 null값만이 존재할 수 있다. 이를 다시 말하면 ActionScript 3.0에서는 더 이상 형을 지정하지 않은 변수는 Object형이 아니라는 것이다. 이는ActionScript 2.0보다 형 변환에 따른 엄격한 규칙을 적용하고 있다고 할 수 있겠다.
글
[AS3] Understanding garbage collection in Flash Player 9
I've been playing around with ActionScript 3.0 for a while now, and I'm really excited by its capabilities. The raw execution speed by itself provides so many possibilities. Toss in E4X, sockets, byte arrays, the new display list model, RegEx methods, a formalized event and error model, and a few dozen other features for flavor, and you have a pretty heady brew.
With great power comes great responsibility, and this is very true for ActionScript 3.0. A side effect of all this new control is that the garbage collector is no longer able to make as many assumptions about what it should automatically tidy up for you. This means that Flash developers moving to ActionScript 3.0 will need to develop a very strong understanding of how the garbage collector operates, and how to work with it effectively. Building even seemingly simple games or applications without this knowledge could result in SWFs that leak like a sieve, hogging all of a system's resources (CPU/RAM) and causing the user's system to hang—potentially even forcing them to hard reboot their computer.
To understand how to optimize your code for ActionScript 3.0, you'll first need an understanding of how the garbage collector works in Flash Player 9. Flash has two processes for finding objects that are not in active use and removing them. This article looks at both techniques and describes how they are relevant to your code.
At the end of this article you can find a simulation of the garbage collector in Flash Player 9 that visually demonstrates the concepts explained herein.
About the garbage collector
The garbage collector is a behind-the-scenes process that is responsible for deallocating the memory used by objects that are no longer in use by the application. An inactive object is one that no longer has any references to it from other active objects. In order to understand this, it is very important to realize that when working with non-primitive types (anything other than Boolean, String, Number, uint, int), you are always passing around a reference to the object, not the object itself. When you delete a variable you remove the reference, not the object itself.
This is easily demonstrated in the code below:
// create a new object, and put a reference to it in a:
var a:Object = {foo:"bar"}
// copy the reference to the object into b:
var b:Object = a;
// delete the reference to the object in a:
delete(a);
// check to see that the object is still referenced by b:
trace(b.foo); // traces "bar", so the object still exists.
If I were to update the code in the example above and delete "b" as well, it would leave my object with no active references and free it for garbage collection. The ActionScript 3.0 garbage collector uses two methods for locating objects with no active references: reference counting and mark sweeping.
Reference counting
Reference counting is one of the simplest methods for keeping track of active objects, and has been used in Flash since ActionScript 1.0. When you create a reference to an object, its reference count is incremented. When you delete a reference, its reference count is decremented. If the reference count of an object reaches zero, it is marked for deletion by the garbage collector.
Here's an example:
var a:Object = {foo:"bar"}
// the object now has a reference count of 1 (a)
var b:Object = a;
// now it has a reference count of 2 (a & b)
delete(a);
// back to 1 (b)
delete(b);
// the reference count down is now 0
// the object can now be deallocated by the garbage collector
Reference counting is simple, it doesn't carry a huge CPU overhead, and it works well in most situations. Unfortunately, the reference counting method for garbage collection is not optimal when it comes to circular referencing. Circular referencing is the situation when objects cross-reference each other (directly, or indirectly via other objects). Even if the application is no longer actively using the objects, their reference counts remain above zero, so the garbage collector never removes them. The code below illustrates how this works:
var a:Object = {}
// create a second object, and reference the first object:
var b:Object = {foo:a};
// make the first object reference the second as well:
a.foo = b;
// delete both active application references:
delete(a);
delete(b);
In the code shown above, both of the active application references have been deleted. I no longer have any way of accessing the two objects from my application, but the reference counts of both objects are 1 because they reference each other. This situation can become much more complex (a references c, which references b, which references a, etc.) and can be difficult to deal with in code. Flash Player 6 and 7 had issues relating to circular referencing in XML objects: each XML node referenced both its children and its parent, so they were never deallocated. Fortunately, Flash Player 8 added a new garbage collection technique called mark and sweep.
Mark sweeping
The second strategy employed by the ActionScript 3.0 (and Flash Player 8) garbage collector to find inactive objects is a method called mark and sweep. Flash Player starts at the root object of your application (which is conveniently called the "root" in ActionScript 3.0) and walks through every reference in it, marking each object it finds.
Next, Flash Player iterates through each of the marked objects. It continues this behavior recursively until it has traversed the entire object tree of your application, marking everything it can reach through an active reference. At the end of this process, Flash Player can safely assume that any objects in memory that are not marked no longer have any active references to them and can be safely deallocated. Figure 1 illustrates how this works: The green references were followed by Flash Player during marking, the green objects are marked, and the white objects will be deallocated.
Mark and sweep is very accurate. However, because Flash Player has to traverse your entire object structure, the process is costly in terms of CPU usage. Flash Player 9 reduces this cost by carrying out iterative mark and sweep—the process occurs over a number of frames, instead of all at once—and by running this process only occasionally.
Deferred garbage collector and indeterminacy
In Flash Player 9, the garbage collector's operations are deferred. This is a very important thing to understand. Your objects will not be removed immediately when all active references are deleted. Rather, they will be removed at some indeterminate time in the future (from a developer standpoint). The garbage collector uses a set of heuristics that look at the RAM allocation and the size of the memory stack, among other things, to determine when to run. As a developer, you must accept the fact that you will have no way of knowing when, or even if, your inactive objects will get deallocated. You must also be aware that inactive objects will continue to execute indefinitely, until the garbage collector deallocates them, so your code will keep running (enterFrame events will continue), sounds will keep playing, loads will keep happening, other events will keep firing, and so on.
It's very important to remember that you have no control over when the garbage collector in Flash Player will deallocate your objects. As a developer, you will want to make the objects in your games and applications as inert as possible when you are finished with them. Strategies to manage this process will be the focus of my companion article, Resource management strategies in Flash Player 9.
Notice the sawtooth pattern of the total memory in the following garbage collection simulation (click Figure 2 or the link below it). The dips are caused when the collector carries out a sweep. Click on the chart to focus it, then press Spacebar to pause or restart, and hold the up/down arrows to change the memory usage trend as it runs.
As shown in the following simulation (click Figure 3 or the link below it), drag out objects (round rectangles) and references to those objects. Then run reference counts or mark and sweep to see which objects would be collected. The number in an object indicates the number of references to that object.
Where to go from here
Understanding garbage collection is going to be one of the most important steps for writing optimized code that ensures that your Flash project runs with minimal impact on the user's computer. Read my companion article, Resource management strategies in Flash Player 9, and visit the Flash Developer Center and Flash Player Developer Center.
Also check out my blog at gskinner.com to read more about weak references and download helper classes that I've written.
About the author
Grant Skinner is the CEO and chief architect of gskinner.com, a Flash development and consulting company. He works with leading new media agencies and progressive corporate clients to create cutting-edge applications, games, and multimedia pieces. His expertise in fusing coding with interface design, usability, marketing, and business logic has garnered him international acclaim and resulted in a number of prestigious industry awards, including Best Canadian Developer at FITC 2005. Grant maintains an active blog at gskinner.com/blog/ and an exhibit of his experimental work at incomplet.org.
국문 : http://www.adobe.com/kr/devnet/flashplayer/articles/garbage_collection.html
글
[AS3] ActionScript 3 Tip of the Day
The release of Flex Builder 2 is around the corner and though the next version of Flash is still a ways away, ActionScript 3 will be a big part of Flex 2 and the impending release of Flash Player 9 (which arrives with Flex). ActionScript 3 is the next step forward and to help with the transition (for those of you deciding to make it), I thought, since I've been working with AS3 a bit lately, I'd make a new Tip of the Day thread for ActionScript 3.0 to help people prepare. So here we go:
ActionScript 3 Tips and Tricks:
- 06-19-06: Change the frame rate of your movie
- 06-20-06: Class scope is now bound to class methods
- 06-21-06: Graphics Object and the Drawing API
- 06-22-06: New Variable Types
- 06-23-06: Display Objects
- 06-24-06: New Import Directive
- 06-25-06: Type Casting and the as Operator
- 06-26-06: Unique Class Variables
- 06-27-06: New MouseMove Behavior
- 06-28-06: The delete Keyword and Class Members
- 06-29-06: The Dictionary Class
- 06-30-06: Label Statements
- 07-01-06: Detecting When the Mouse Leaves the Movie
- 07-02-06: SimpleButton Instances
- 07-03-06: Commas in Shorthand Array Definitions
- 07-04-06: Package Block
- 07-05-06: Same-file Helper Classes
- 07-06-06: Access Attributes
- 07-07-06: Abstract Classes
- 07-08-06: The override Keyword
- 07-09-06: Using prototype
- 07-10-06: Regular Expression (RegExp) Support
- 07-11-06: Approach to Depth Sorting
- 07-12-06: Deep Object Copies with ByteArray
- 07-13-06: Similarly Named Instance and Static Properties
- 07-14-06: EventDispatcher
- 07-15-06: Events and Event Types
- 07-16-06: Writing Inline XML
- 07-17-06: Determine Instance Class or Superclass
- 07-18-06: super() Placement (Now Anywhere)
- 07-19-06: Determining Current Frame Label
- 07-20-06: Multiple Arguments in trace()
- 07-21-06: Calling Event Handlers without Events
- 07-22-06: URLRequest for URL Strings
- 07-23-06: XML vs. XMLDocument
- 07-24-06: Loading Text and XML with URLLoader
- 07-25-06: is Operator (vs instanceof)
- 07-26-06: Flash 9: Timelines as Classes
- 07-27-06: RegExp: Email Validation
- 07-28-06: Render Event
- 07-29-06: XML: @ Operator for Attributes
- 07-30-06: Event Propagation Support
- 07-31-06: Get Sound Spectrum Information
- 08-01-06: Number() Conversion No Longer Interprets Octals
- 08-02-06: Garbage Collection: Reference Counting & Mark and Sweep
- 08-03-06: Weak References
- 08-04-06: Flash 9: BitmapData and Bitmaps from the Library
- 08-05-06: Changes in typeof
- 08-06-06: getBounds() vs getRect()
- 08-07-06: for..in and for each..in
- 08-08-06: Default Values for Function Parameters
- 08-09-06: Undetermined Number of Arguments With ...(rest)
- 08-10-06: arguments
- 08-11-06: Support for Namespaces
- 08-12-06: Namespaces: Name Qualifier Operator (::)
- 08-13-06: dynamic is Not Inherited
- 08-14-06: Creating a mouseWithin Event
- 08-15-06: Prevent Overriding and Subclassing with final
- 08-16-06: MXMLC: SWF Metadata Tag
- 08-17-06: Proxy Class
- 08-18-06: in Operator
- 08-19-06: Proxy: getProperty and setProperty
- 08-20-06: Flash 9: Display Object Variables and Instance Names
- 08-21-06: XML: XML and XMLList
- 08-22-06: Constants
- 08-23-06: duplicateMovieClip Replacement
- 08-24-06: Proxy: callProperty
- 08-25-06: Creating graphics Copies
- 08-26-06: TextField.appendText()
- 08-27-06: include Directive
- 08-28-06: Duplicate Variable Definitions
- 08-29-06: mouseEnabled and Event Blocking
- 08-30-06: mouseChildren with Event Propagation
- 08-31-06: rollOver and rollOut vs. mouseOver and mouseOut
- 09-01-06: DisplayObjectContainer contains()
- 09-02-06: Cleaning Up Event Listeners
- 09-03-06: Detecting Addition to or Removal from Stage
- 09-04-06: Event Phases and Event Capturing
- 09-05-06: Determining Event Phase
- 09-06-06: Preventing Event Propagation
- 09-07-06: Global Events
- 09-08-06: Detecting a mouseUp Outside
- 09-09-06: Flash 9: Document Class
- 09-10-06: Access to stage and root
- 09-11-06: Namespaces: use namespace Directive
- 09-12-06: No More Color Class; Use ColorTransform
- 09-13-06: Runtime Errors; Error Class
- 09-14-06: Errors: try..catch..finally and Exception Handling
- 09-15-06: Errors: Asynchronous Exception Handling
- 09-16-06: XML: Children (.) and Decendants (..)
- 09-17-06: Array.indexOf (Array.lastIndexOf())
- 09-18-06: asfunction: Now event:
- 09-19-06: Proxy: Property Enumeration (nextName(), nextValue(), and nextNameIndex())
- 09-20-06: Event Capturing and mouseEnabled
- 09-21-06: Flash 9: Strict Mode
- 09-22-06: System.totalMemory
- 09-23-06: Closing Net Connections
- 09-24-06: Timer Class
- 09-25-06: AVM2 (AS3) to AVM1 (AS2/AS1) Communication via LocalConnection
- 09-26-06: ByteArray Class
100 AS3 tips! After tip 100, no longer will they be added daily
글
[AS3] ActionScript 3.0 첫 프로그래밍
간단한 코딩이지만 직접 접하고 보니 이제야 비로소 정리가 되는 듯 하다. 기존에 호환성 문제로 인해서 불필요하게 사용되었던 군더더기가 많이 빠지고 깔끔해 졌다는 느낌이다. 형식적이고 자율적인 구조로 인해서 혼돈이 왔던 부분들은 간결한 형태로 변화되었고 그 형태 또한 만족스럽다.
하지만 그 동안 편리하게 사용되었던 기능들도 그러한 진화를 바탕으로 다소 불편한 부분도 없지 않다. 그러나 그 불편함 또한 개발자에게 동기와 목적을 확실하게 이미지화 하기 때문에 납득할 만한 변화라는 생각이다.
앞으로 플래시를 사용하는 모든 분야의 발 빠른 변화가 상당히 재미있어질 것 같다…
// Rec.as