by Ryan Green
I’ve spent most of my career on the web. Well, my first real job was as busboy at a local mexican hole-in-the-wall restaurant (love the salsa.) Then as proud crew member of a certain fast-food burger joint with golden arches (click here to skip to the meat of this post), then, as up and coming young web designer. It is amazing the job you could land in the dot-com bubble with some decent photoshop know-how and a copy of Microsoft Frontpage…
Anyhow, what I quickly learned in my stint as web master, besides the art of pixel perfect nested HTML table layouts so that my webpages could load inside the 1990’s on a 28.8 baud modem, was that if you wanted to give your customers any value besides a relatively accurate re-creation of their 4 page full-color brochure, you needed to know databases and some form of server side scripting.
I chose Cold Fusion. At the time this was due to the fact that it was the only book in our little office that didn’t have the letters ‘CGI’ and ‘Perl’ in the title. Cold Fusion provided some nice tag based syntax for connecting with a database and displaying tractor parts in a webpage. Then came Javascript and DHTML and VBScript and PHP and then, at last, Actionscript 1 & 2.
Now, lest you fear I die a quick death stuffed to the gills with obscure scripting language knowledge, Actionscript 3 arrived with Flex just in time to spare me the wrath of Java nerds hailing the death of ColdFusion and other “non-languages.” The language of the User Interface has steadily matured into Object-Oriented like syntax and smarter uses of XML to define the UI, and the “real-programmers” have moved native with Objective-C/C++/C#/C-flat and C#-minor. Oh, and don’t forget Java on that little mobile platform called Android… and how dare I forget ruby and python.
All this to say that, in this day-and-age, we face a fragmented amalgamation of languages and platforms all vying for title of “most-awesome-real-language.”
Well, my nomination for new entrant into the “real-language” lexicon is Actionscript/MXML, a syntax that gives Javascript its Object-Orientation and the HTML tag actual namespaces and custom tag names.
Syntax Differences in Objective-C/C/C++ and Actionscript 3
Actionscript is a product of the ECMA Script specification which is, in turn, part of the C programming language family. In basic syntax (operators, conditional statements and enumeration), Objective-C and Actionscript are almost identical.
Objective-C/C/C++ | Actionscript 3 | |
Calculation | +, -, /, *, ++ (increment), -- (decrement), % (modulo) | Same |
Assignment | = | Same |
Comparison | ==, !=, ===, !==, >, <, >=, <= | Same |
Comment | /* */, // | Same plus <!-- --> for MXML |
Logical | &&, ||, ! | Same |
Null | nil (use to compare with Objective-C objects) NULL (use to compare with everything else) | null |
If Statement | if(condition) { } | Same |
Switch/Case | switch(expression) { } | Same |
Fast Enumeration | for(Type newVariable in collection) { } | for(var value:Type in collection) { } |
Do / While | while(expression) { } | Same |
For | for(int value = start; value <= end; value++) { } | for(var value:int = start; value <= end; value++) { } |
Ternary | return (i > 0) ? true : false; | Same |
Where the languages start to diverge is in how they instantiate and declare variables and methods and how they message objects.
Primative Types
Objective-C/C/C++ | Actionscript 3 | |
Data Type Documentation | ||
Boolean | BOOL mine = YES; BOOL mine = NO; | var mine:Boolean = true; var mine:Boolean = false; |
Integer | int i = 1; | var i:int = 1; |
Float | float pi = 3.14; | var pi:Number = 3.14; |
String | NSString *fname = @”Ryan”; | var fname:String = “Ryan”; |
Declaring Classes
Objective-C/C/C++ | Actionscript 3 | |
Documentation | Declaring Classes Documentation | Declaring Classes Documentation |
Declare Class |
| //-- File ClassName.as package {
//constructor public function ClassName():void {
|
Declaring Variables
Objective-C/C/C++ | Actionscript 3 | |
Declaring Variables Documentation | ||
Instance Variables (accessible outside class) | //-- File ClassName.h @end
@synthesize variableName; @end | //-- File ClassName.as public class ClassName {
return _variableName; } public function set variableName(value:Type):void { _variableName = value; } }
or
|
Static Class Variables | //-- File ClassName.h @end
static Type *variableName; +(Type *)variableName { return variableName; } +(void)variableName: (Type *)newVar {
| //-- File ClassName.as public static var variableName:Type;
|
Local Variables | (int) i;
| var i:int;
|
Access Properties | obj.propertyName; obj->propertyName; | obj.propertyName; |
Implementing Methods/Functions
Objective-C/C/C++ | Actionscript 3 | |
Declaring Functions Documentation | ||
@interface {} @end
| public function methodName(arg1:Type, arg2:Type):Type { } |
Implementing Getters/Setters
Objective-C/C/C++ | Actionscript 3 | |
Getter/Setter Documentation | ||
@synthesize propertyName;
| /* getter/setter functions may not have return _propertyName;
_propertyName = value;
|
Class Instantiation
Objective-C/C/C++ | Actionscript 3 | |
Type *class = [[Type alloc] init]; | var class:Type = new Type(); |
Handling Basic Data Types
In general Actionscript objects are always mutable and like Objective-C, Actionscript is reflective.
Reflection
Objective-C/C/C++ | Actionscript 3 | |
Documentation | Reflection Documentation (examples referenced) | |
Class Declaration | Class cls = NSClassFromString(@"Foo"); | var class:Class = getDefinitionByName("Foo") as Class; var foo:Class = new class(); |
Call Dynamic Method | SEL selector = NSSelectorFromString(@"hello"); [foo performSelector:selector withObject:nil]; | foo["hello"](); |
Handling Strings
Objective-C/C/C++ | Actionscript 3 | |
Documentation | NSString Class Documentation | String Class Documentation |
Declaration | NSString * str = @"The quick brown fox"; | var str:String = "The quick brown fox"; |
Concatenation | NSString * str2 = [str stringByAppendingString: @"jumped ..."]; | str = str + " jumped over the lazy river"; |
Replace | NSString * final = [start stringByReplacingOccurancesOfString: @"find" | str = str.replace('find', 'replace'); |
Search | NSRange *range = [myString rangeOfString: @"string to find"]; //returns {NSNotFound, 0} if not found | var idx:int = str.indexOf('string to find'); // returns -1 if not found; |
Substring | NSString *str2 = [str substringWithRange: NSMakeRange (0, 1)]; | var sub:String = ("string").substr(0, 1); trace(sub); //<-- outputs "s" |
Comparison | NSComparisonResult result = [str compare: @"first"]; // result == YES | var str:String = "first"; trace(b); //<-- outputs "true" |
Handling Arrays
Objective-C/C/C++ | Actionscript 3 | |
Documentation | NSMutableArray Class Documentation | Array Class Documentation ArrayCollection Class Documentation |
Declaration | NSArray *a = [[NSArray alloc] initWithObjects: @"apple", @"orange", @"grape"]; [b addObjectsFromArray: a];
| var a:Array = ["apple","orange","grape"]; var a:Array = new Array(); |
Add Element at end | [a addObject: @"lemon"]; | a.push("lemon"); |
Add Element at beginning | [a insertObjectAtIndex: @"lemon"]; | a.unshift("lemon"); |
Remove Element at end | [a removeLastObject]; | var fruit:String = a.pop(); |
Remove Element at beginning | [a removeObjectAtIndex: 0]; | var fruit:String = a.shift(); |
Access Element at Index | [a objectAtIndex: 0]; | var a:Array = ["apple", "pear"]; trace(a[1]); //<-- outputs "pear" |
Remove Element at Index | [a removeObjectAtIndex: 1]; | var a:Array = ["apple", "pear", "peach"]; a.splice(1, 1); |
Length of Array | [a count]; | var a:Array = [0, 1, 2, 3, 4]; trace(a.length); //<-- outputs "5" |
Handling Dictionary Objects
Objective-C/C/C++ | Actionscript 3 | |
Documentation | NSMutableDictionary Class Documentation | Object Class Documentation Dictionary Class Documentation |
Declaration | NSMutableDictionary *dict = NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; | var object:Object = {firstname:"Ryan", var object:Object = new Object(); |
Set Object for Key | [dict setObject: @"D" forKey: @"middleinitial"]; | object.middleinitial = "D"; object["middleinitial"] = "D"; |
Remove Object for Key | [dict removeObject: @"D" forKey: @"middleinitial"]; | delete object.middleinitial; |
Get Object By Key | [dict objectForKey: @"middleinitial"]; | if(object.hasOwnProperty('middleinitial')) { } |
Terminators / Cleanup
Ahh, now you’ve caught me. Actionscript is one of those languages that does not allow for direct garbage collection. However, if you successfully release all references to your object, Flash promises to garbage collect… eventually.
Objective-C/C/C++ | Actionscript 3 | |
Release Memory | [object release]; | delete object; |
Putting it All Together
Objective-C/C/C++ | Actionscript 3 | |
Favorite Foods interface | //-- File FavoriteFoods.h }
-(void)addFavoriteFood:(NSString *)food; +(BOOL)badForMe:(NSString *)food howMany: (int)count; @end
|
|
Favorite Foods class | //-- File FavoriteFoods.m return YES;
} else { return NO;
[foods release]; }
| //-- File FavoriteFoods.m }
foods.push(food);
if(food == "1 pound hamburger) { switch(count) { case 0: case 1: return false; break; default:
else { return false; }
|
Manage Favorite Foods class | //-- File ManageFavoriteFoods [favorites release]; | //-- File ManageFavoriteFoods delete favorites; |
Ok, so this was a pretty high level flyby of Actionscript syntax. What I think you’ll find in using AS3 is that it is very Javascript-like and less verbose than Objective-C, however when combined with the Flex SDK, I believe you’ll find a corollary in Flex to most Objective-C features.
What I found in a previous porting project from iPhone and Objective-C to Flex and AS3, was that in many cases the logic and syntax of the non UI code (that is class structure, logic and graphic APIs) was a nearly direct port. I found myself copying and pasting C code and simply fixing the syntax. This is the power of a code base like Flex over classic Flash development. In Flex, there is no timeline or stage in which to store snippets of code in frames and under buttons. Because of this, Flex can offer ‘real-programmers’ a much more comfortable transition into flash programming through Object-Oriented syntax and a class based code structure.
Stay Tuned, in my next installment we’ll be getting into the meat of the SDKs and comparing/contrasting UI patterns and implementation differences so that you have a path for porting User Interface from Cocoa to Flex.
If you missed part 1 of this series, I welcome you to check it out. In the first article I introduce Flash and provide a high-level comparison between the Cocoa and Flex SDKs.
———-
This post first appeared on the Intel AppUp Developer site here: http://appdeveloper.intel.com/en-us/article/porting-iphone-netbook-flex-understanding-syntax-actionscript-and-mxml
And it also looks dreadful in this template…