[AS3] for each..in 문법

Programming/ActionScript 3.0 2007. 6. 15. 04:04
var myObj:Object = {x:20, y:30};
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 형의 독립

Programming/ActionScript 3.0 2007. 6. 15. 03:24
ActionScript 2.0에서는 아래의 경우 1번과 2번은 같은 형으로 정의하게 되는데 이는 형을 지정하지 않은 변수의 경우는 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

Programming/ActionScript 3.0 2007. 6. 13. 11:17

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.

Objects that no longer have active references are identified by Flash Player using the mark and sweep method

Figure 1. Objects that no longer have active references are identified by Flash Player using the mark and sweep method

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.

Garbage collection simulation

Figure 2. Garbage collection simulation

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.

Garbage collection simulation: mark and sweep

Figure 3. Garbage collection simulation: mark and sweep

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

Programming/ActionScript 3.0 2007. 6. 13. 10:03
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:
  1. 06-19-06: Change the frame rate of your movie
  2. 06-20-06: Class scope is now bound to class methods
  3. 06-21-06: Graphics Object and the Drawing API
  4. 06-22-06: New Variable Types
  5. 06-23-06: Display Objects
  6. 06-24-06: New Import Directive
  7. 06-25-06: Type Casting and the as Operator
  8. 06-26-06: Unique Class Variables
  9. 06-27-06: New MouseMove Behavior
  10. 06-28-06: The delete Keyword and Class Members
  11. 06-29-06: The Dictionary Class
  12. 06-30-06: Label Statements
  13. 07-01-06: Detecting When the Mouse Leaves the Movie
  14. 07-02-06: SimpleButton Instances
  15. 07-03-06: Commas in Shorthand Array Definitions
  16. 07-04-06: Package Block
  17. 07-05-06: Same-file Helper Classes
  18. 07-06-06: Access Attributes
  19. 07-07-06: Abstract Classes
  20. 07-08-06: The override Keyword
  21. 07-09-06: Using prototype
  22. 07-10-06: Regular Expression (RegExp) Support
  23. 07-11-06: Approach to Depth Sorting
  24. 07-12-06: Deep Object Copies with ByteArray
  25. 07-13-06: Similarly Named Instance and Static Properties
  26. 07-14-06: EventDispatcher
  27. 07-15-06: Events and Event Types
  28. 07-16-06: Writing Inline XML
  29. 07-17-06: Determine Instance Class or Superclass
  30. 07-18-06: super() Placement (Now Anywhere)
  31. 07-19-06: Determining Current Frame Label
  32. 07-20-06: Multiple Arguments in trace()
  33. 07-21-06: Calling Event Handlers without Events
  34. 07-22-06: URLRequest for URL Strings
  35. 07-23-06: XML vs. XMLDocument
  36. 07-24-06: Loading Text and XML with URLLoader
  37. 07-25-06: is Operator (vs instanceof)
  38. 07-26-06: Flash 9: Timelines as Classes
  39. 07-27-06: RegExp: Email Validation
  40. 07-28-06: Render Event
  41. 07-29-06: XML: @ Operator for Attributes
  42. 07-30-06: Event Propagation Support
  43. 07-31-06: Get Sound Spectrum Information
  44. 08-01-06: Number() Conversion No Longer Interprets Octals
  45. 08-02-06: Garbage Collection: Reference Counting & Mark and Sweep
  46. 08-03-06: Weak References
  47. 08-04-06: Flash 9: BitmapData and Bitmaps from the Library
  48. 08-05-06: Changes in typeof
  49. 08-06-06: getBounds() vs getRect()
  50. 08-07-06: for..in and for each..in
  51. 08-08-06: Default Values for Function Parameters
  52. 08-09-06: Undetermined Number of Arguments With ...(rest)
  53. 08-10-06: arguments
  54. 08-11-06: Support for Namespaces
  55. 08-12-06: Namespaces: Name Qualifier Operator (::)
  56. 08-13-06: dynamic is Not Inherited
  57. 08-14-06: Creating a mouseWithin Event
  58. 08-15-06: Prevent Overriding and Subclassing with final
  59. 08-16-06: MXMLC: SWF Metadata Tag
  60. 08-17-06: Proxy Class
  61. 08-18-06: in Operator
  62. 08-19-06: Proxy: getProperty and setProperty
  63. 08-20-06: Flash 9: Display Object Variables and Instance Names
  64. 08-21-06: XML: XML and XMLList
  65. 08-22-06: Constants
  66. 08-23-06: duplicateMovieClip Replacement
  67. 08-24-06: Proxy: callProperty
  68. 08-25-06: Creating graphics Copies
  69. 08-26-06: TextField.appendText()
  70. 08-27-06: include Directive
  71. 08-28-06: Duplicate Variable Definitions
  72. 08-29-06: mouseEnabled and Event Blocking
  73. 08-30-06: mouseChildren with Event Propagation
  74. 08-31-06: rollOver and rollOut vs. mouseOver and mouseOut
  75. 09-01-06: DisplayObjectContainer contains()
  76. 09-02-06: Cleaning Up Event Listeners
  77. 09-03-06: Detecting Addition to or Removal from Stage
  78. 09-04-06: Event Phases and Event Capturing
  79. 09-05-06: Determining Event Phase
  80. 09-06-06: Preventing Event Propagation
  81. 09-07-06: Global Events
  82. 09-08-06: Detecting a mouseUp Outside
  83. 09-09-06: Flash 9: Document Class
  84. 09-10-06: Access to stage and root
  85. 09-11-06: Namespaces: use namespace Directive
  86. 09-12-06: No More Color Class; Use ColorTransform
  87. 09-13-06: Runtime Errors; Error Class
  88. 09-14-06: Errors: try..catch..finally and Exception Handling
  89. 09-15-06: Errors: Asynchronous Exception Handling
  90. 09-16-06: XML: Children (.) and Decendants (..)
  91. 09-17-06: Array.indexOf (Array.lastIndexOf())
  92. 09-18-06: asfunction: Now event:
  93. 09-19-06: Proxy: Property Enumeration (nextName(), nextValue(), and nextNameIndex())
  94. 09-20-06: Event Capturing and mouseEnabled
  95. 09-21-06: Flash 9: Strict Mode
  96. 09-22-06: System.totalMemory
  97. 09-23-06: Closing Net Connections
  98. 09-24-06: Timer Class
  99. 09-25-06: AVM2 (AS3) to AVM1 (AS2/AS1) Communication via LocalConnection
  100. 09-26-06: ByteArray Class


100 AS3 tips! After tip 100, no longer will they be added daily

    

설정

트랙백

댓글

[AS3] ActionScript 3.0 첫 프로그래밍

Programming/ActionScript 3.0 2007. 6. 13. 02:36
늦은 감이 없지 않지만 처음으로 AS3를 가지고 코딩을 해봤다. 간단한 결과물이지만 여러 가지로 사소한 것부터 이벤트 처리에 이르기까지 적지 않게 AS2에서 AS3으로 migration한 것을 볼 수가 있는데 이 결과물을 만들고 보니 참 재미있다는 생각이 든다. 플래시의 actionscirpt의 변천사를 보면 참으로 잘 짜여진 시나리오라는 생각과 동시에 엄청난 잔머리의 위대함이라는 생각도 들기 때문이다.

간단한 코딩이지만 직접 접하고 보니 이제야 비로소 정리가 되는 듯 하다. 기존에 호환성 문제로 인해서 불필요하게 사용되었던 군더더기가 많이 빠지고 깔끔해 졌다는 느낌이다. 형식적이고 자율적인 구조로 인해서 혼돈이 왔던 부분들은 간결한 형태로 변화되었고 그 형태 또한 만족스럽다.

하지만 그 동안 편리하게 사용되었던 기능들도 그러한 진화를 바탕으로 다소 불편한 부분도 없지 않다. 그러나 그 불편함 또한 개발자에게 동기와 목적을 확실하게 이미지화 하기 때문에 납득할 만한 변화라는 생각이다.

앞으로 플래시를 사용하는 모든 분야의 발 빠른 변화가 상당히 재미있어질 것 같다…

[Flash] http://jasu.tistory.com/attachment/cfile30.uf@222F35385880210F23FEAD.swf





// Rec.as
package{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;

public class Rec extends MovieClip{
public function Rec(){
trace(this.name +" is created");
this._mc.buttonMode = true;
this._mc.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
this._mc.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
this._mc.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
this._mc.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
this._mc.addEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler);
}
private function mouseDownHandler(event:MouseEvent):void{
trace(this.name + " : mouseDownHandler");
this.startDrag();
}
private function mouseOutHandler(event:MouseEvent):void{
trace(this.name + " : mouseOutHandler");
var myTween:Tween = new Tween(this, "scaleX", Elastic.easeInOut, this.scaleX, 1, 1, true);
var myTween2:Tween = new Tween(this, "scaleY", Elastic.easeInOut, this.scaleY, 1, 1, true);
}
private function mouseOverHandler(event:MouseEvent):void{
trace(this.name + " : mouseOverHandler");
var topPosition:uint = this.parent.numChildren - 1;
this.parent.setChildIndex(this, topPosition);
var myTween:Tween = new Tween(this, "scaleX", Elastic.easeInOut, this.scaleX, 1.4, 0.7, true);
var myTween2:Tween = new Tween(this, "scaleY", Elastic.easeInOut, this.scaleY, 1.4, 0.7, true);
}
private function mouseUpHandler(event:MouseEvent):void{
trace(this.name + " : mouseUpHandler");
this.stopDrag();
}
private function mouseWheelHandler(event:MouseEvent):void{
trace(this.name + " : mouseWheelHandler");
}
}
}

// RecDocumentClass

package{
import flash.display.Sprite;
import flash.display.MovieClip;
public class RecDocumentClass extends MovieClip{
private var rootChild:Sprite;
public function RecDocumentClass(){
rootChild = new Sprite();
addChild(rootChild);
init();
}
private function init():void{
var Rec1:Rec = new Rec();
Rec1.x = Rec1.y = 100;
rootChild.addChild(Rec1);

var Rec2:Rec = new Rec();
Rec2.x = Rec2.y = 200;
rootChild.addChild(Rec2);

}
}
}





    

설정

트랙백

댓글

AS3 API 계층구조도

Programming/ActionScript 2.0 2007. 2. 21. 10:57
AS3 API 계층구조 자료



 = new EXE(new SWF(new JPG(PDF))); 입니다.

    

설정

트랙백

댓글