Cocoa touch for actionscript developers (basics)
So in the (near) future i will discuss some iphone SDK topics seen through the eye of an Actionscript developer. so what I’m planning to do is take a real live example (e.g.: Array Sorting, loading XML, drawing,..) and provide you with the actionscript version and convert it to objective C / iphone SDK, if there are some specific topics .. just leave a comment and i will definitely consider blogging about it.
It will be a series of specific topics, for the general work-flow/development I recommend you to use google or youtube. My topics will be mainly focused on developing with the iphone sdk through the eyes of an Actionscript mind.
But before we start our first topic i would like to give some basic knowledge about obj-c.
Objects
So for example we have an Object which describes some person information.
#Actionscript package { public class Person extends Object { private var _name : String; private var _age : int; public function Person(name:String, age:int) { _name = name; _age = age; } public function get name() : String { return _name; } public function get age() : int { return _age; } public function set name( value : String ) : void { _name = value; } public function set age( value : int ) : void { _age = value; } } } package { import Person; import flash.display.Sprite; public class Main extends Sprite { public function Main() { var person : Person = new Person( "John", 32 ); trace( person.name, person.age ); } } }
So what we have done is create a very simple object where we can store 2 variables.
Which we trace in Main class, so the output would be “John 32″
Now lets convert that to Objective C
Person.h #import @interface Person : NSObject { NSString *name; int age; } @property (nonatomic,retain) NSString *name; @property (readwrite) int age; @end Person.m #import "Person.h" @implementation Person @synthesize name,age; @end
So for the creation of objects / classes you have 2 files, the interface and the implementation. In the interface part we describe the different module variables and functions. But also the type of the object and which delegates/controls the object should implement.
Apple discourages the use of an underscore as a prefix for a private instance variable. The idea of a private prefix is largely unnecessary, as virtually all instance variables in Cocoa are protected anyway.
The asterix in front of “name” tells me the variable “name” is a pointer (”Pointers are designed to hold memory addresses. With a pointer you can indirectly manipulate data stored in other variable.”) I’m not going to explain the in’s and out’s of pointers but if you like to read more about it i suggest you to read this page (its written in C but has the same principles) http://home.netcom.com/~tjensen/ptr/pointers.htm
We declare the property’s and define their parameters. If you like to know more about the different parameters i used (http://www.cocoacast.com/?q=node/103)
In the implementation file we synthesize our variables: The @synthesize directive generates accessor methods for us. ( at the given parameters which are declared by the property )
Main Application (Just choose the template for a window based application, i’m only going to discuss the creation of our Person object) (just replace the applicationDidFinishLaunching method)
- (void)applicationDidFinishLaunching:(UIApplication *)application { // Override point for customization after application launch [window makeKeyAndVisible]; //init Person Person *person = [Person alloc]; person.age = 32; //person.name = @"John"; [person setName:@"John"]; NSLog(@"%@ %i",person.name,[person age]); [person release]; NSLog(@"%@ %i",person.name,[person age]); }
So as we can see we need to allocate the variable in the memory,
as we are familiar with in actionscript
New Person(); -> is the same als [Person alloc] (if we want to call the constructor we normally would use [[Person alloc] init])
Since objective C 2 we can access our variables with -dot notation or you can either use the two accessor forms
NSLog is the equivalent of trace in Actionscript .. we define what types we want to output and just pass the paramaters.
@”" defines a string
%@ lets the formatter know he would expect a string
%i lets the formatter know he would expect an integer
if we release the object from the memory it can not be accessed any more
output should be:
2008-12-02 12:21:42.323 basics[1781:20b] John 32
objc[1781]: FREED(id): message age sent to freed object=0×522220
Methods
So we are going to continue our previous example I’m going to add 3 functions
#Actionscript public function myNameLength() : int { return _name.length; } public function myBodyMassIndex( length : Number, weight : Number ) : String { return "My BMI is: " + roundTo((weight / (length * length)),2); } private static function roundTo( value : Number, n : Number ) : Number { var aft : int = Math.pow(10, n); return Math.round(value*aft)/aft; }
#Objective C Person.h #import @interface Person : NSObject { // variables } //properties -(int)myNameLength; -(NSString *)myBodyMassIndexWithLength:(float)length weight:(float)weight; +(float)roundToWithValue:(float)bmi DigitsAfterPoint:(int)dap; @end Person.m #import "Person.h" #import "Math.h" @implementation Person @synthesize name,age; -(int)myNameLength{ return [name length]; } -(NSString *)myBodyMassIndexWithLength:(float)length weight:(float)weight{ float bmi = (weight/(length*length)); return [NSString stringWithFormat:@"My BMI is: %f - rounded BMI: %f",bmi,[Person roundToWithValue:bmi DigitsAfterPoint:2]]; } +(float)roundToWithValue:(float)bmi DigitsAfterPoint:(int)dap{ float aft = pow(10,dap); return round(bmi*aft)/aft; } @end
So we have 3 functions 2 public functions 1 static in Actionscript.
At the Objective-C side of the story
We have 3 methods 2 “instance” Methods and 1 “class” Method(The minus sign before (int) indicates that this method is an “instance” method. If it were a plus, it would indicate that it is a class method. You could see it more or less like public/static functions in Actionscript)
We usually define them under the @property’s in the interface
We can’t actually declare if our methods are private or public and we don’t have to specify a “separate method name” we can just add our parameters. As seen clearly in the second and third method.
for the return value we use a class Method(stringWithFormat) of the class NSString to format our string,
stringWithFormat:@"My BMI is: %f - rounded BMI: %f",bmi,[Person roundToWithValue:bmi DigitsAfterPoint:2]
@” <- start of the string
%f <- expects a float (format specifiers)
most common
%@ Object
%d, %i signed int
%u unsigned int
%f float/double
so for all the format specifiers: we add a parameter.
For the last function we specified a class method.
that uses some functions of the Math.h ( so don’t forget the #import “Math.h” at the top)
NSLog(@"%i",[person myNameLength]); NSLog(@"%@",[person myBodyMassIndexWithLength:1.7 weight:51]); NSLog(@"%f",[Person roundToWithValue:20.796434234 DigitsAfterPoint:3]);
So now if we add those NSLog statements to our applicationDidFinishLaunching method you get the exact logs
We use [<our object> <ourmethod>:<paramaters] to access our “instance” methods
- like shown in the first 2 NSLog statements
We use [<our Class> ourmethod:<paramaters] to access our “class” methods
- like shown in the last 2 NSLog statements
So that’s it for now,See you in a next tutorial
Hi Andy,
very nice blogpost, looking forward seeing you present it one day
keep up the good work dude on native and ajax based iphone development!
See you for lunch!
Thomas Joos – Boulevart
It actually will be this afternoon
check your mail
hi Andy,
just wanted to say I liked your presentation, you did a good job, how is the fitc content going?
[...] tutorial: Cocoa Touch Basics for Actionscript developers Hello there, I’m an Actionscript Developer and I’ve set out the basic principles for learning cocoa touch (objective c) through the eyes of a Actionscript developer (JavaScript or Java have a similar base / structure ). I have only 1 topic online ( the basics ) but I’m planning to do a whole series of them. if you have any feedback or suggestions or requests .. let me know Andy Jacobs
[...] leave a comment » Andy Jacobs Last week, a former multimedia classmate / Boulevart colleague / friend of mine, started with a very cool initiative for actionscript developers who are interested in iphone development. On his new blog Andy will discuss some iphone SDK topics seen through the eye of an Actionscript developer. Andy will take real live examples (e.g.: Array Sorting, loading XML, drawing,..) and provide you with the actionscript version and convert it to objective C / iphone SDK. A perfect guideline for actionscript developers who are interested getting started with cocoa touch! If you are one of them this is the place to go: Cocoa touch for actionscript developers. [...]
Great stuff;
As a habitual user of AMFPHP, I’d be very interested in knowing how one might connect dataservices with php. Are there binary protocols available (surely not AMF..) other than xml and http POST/GET?
thanks
@RansomWeaver
Wich protocols would you like to see covered? REST / SOAP / .. ?
I don’t think there is an existing AMF serialization/deserialization api available for Objective-C. but if your looking for a similar protocol. Since AMF is loosely based on SOAP, i can do a topic about SOAP ..
i was thinking I really enjoy the ease of hooking up AMFPHP…. Where to start in implementing a client-server service based system where data is kept in e.g. mysql for an iphone app? If you think SOAP that’d be great!
Then again on further exploring I see that both iphone and php have good json support, so maybe that’s the way to go and avoid xml altogether.
http://www.ibm.com/developerworks/opensource/library/os-php-v523/
http://iphonedevelopertips.com/cocoa/json-framework-for-iphone-part-2.html
Even better!
amfphp 1.9 has a json.php gateway which will return your existing amfphp services as json instead of amf. url format for the service request looks like: amfphp/json.php/MyClass.myMethod/arg1/arg2 where MyClass.php is in the amfphp services dir, with the remote methods inside that.
then using the iphone JSON framework it looks pretty easy to bring it in as a NSDictionary.
nice to know
thanks for the tip.
i will do a comparison on how to load json into the iphone, later on (since it’s Christmas, it is very hectic around here but i will try to put it online as soon as possible).
[...] Jacobs: “Cocoa touch for actionscript developers (basics)“, “AS3 to Cocoa Touch: Array’s“, “AS3 to Cocoa touch: XML“, [...]
[...] The Basics – An initial comparison of how objects are put together using Objective C and ActionScript. [...]
Don’t get in the habit of not sending the -init message, or the appropriate initializer, to newly allocated objects. You almost never want to use an object that has only been allocated.
I just fell in love with another man. That hurts to say. I am an Actionscript developer partnered with an iPhone application developer.
We’ve got one application on the market now, and as it continues to grow in scope, I find myself becoming less useful on the code side of things.
I will definitely be following your Actionscript to Objective articles closely, and appreciate you doing this.
Nice and simple tutorial, I’m primarily a flash developer slowly but surely learning the ins and outs of cocoa and iphone development and your blog has been proven to be very helpful.
I was just wondering if you’ve found a way to eliminate the date stamp that exists before the NSLog output window so it just outputs
‘foo’
instead of
”2008-12-02 12:21:42.323 basics[1781:20b] foo’.
This article is the most helpful I’ve found so far in helping me bridge my AS3 to Objective C — thank you for taking the time to share your expertise.
Your blog is very interresting for me, i will come back here..