Archive for December, 2008

AS3 to Cocoa touch: JSON (Part 1: load json)

Posted in as3, cocoa touch, iphone, objective c on December 24th, 2008 by admin – 9 Comments

So in this tutorial I’m going to discuss what would be a possible way to  transfer your data from a backend to your iphone. I have 2 primary things I have in mind doing this what are very important to me. It must be easy to implement (in the backend as well as in objective-c), And I need a format that is accessible from many program languages / approaches.
So from that point on I stumbled upon the use of JSON. It’s very easy in use, support for many languages (http://json.org). My Actionscript mind would always put amf in favor since its very well supported in actionscript and the flash player. As well as the backend side of the story ( fluorine, amfphp, weborb, blazeds, livecycle, ..).

The usercase that I came in contact with the most was, get something out of a database with php convert it to amf with amfphp or weborb and send it over to flash. So that’s the usercase I want to take as an example to do the comparison. So what is my setup ?

read more »

AS3 to Cocoa touch: XML

Posted in as3, cocoa touch, iphone, objective c on December 18th, 2008 by admin – 9 Comments

For this tutorial were going to discus XML Parsing. I’m not totally fond of the xml functionality’s in objective c. I use XML all the time in actionscript because its so easy and powerfull with E4X.  Although there are some open source initiatives for xml parsing. I find it hard to implement them into my projects so I keep it with the standard XML class provided by the cocoa touch framework. So we NSXMLParser, and.. oh wait that’s the only one. NSXMLDocument, NSXMLElement, .. won’t work on the iphone, I didn’t test it but what I have read on the forums about it will work in the iphone simulator but not on the iphone itself. ( by the way if someone knows a great/simple api for xml parsing on the iphone let me know ;-) )

So for this tutorial we are going to stick with the NSXMLParser class.
Actually the NSXMLParser isn’t so bad at all if you start working with it.
The basic idea behind the NSXMLParser class is that it iterates through every element in your XML.
And it uses a Delegate to invoke the methods needed but that will become more clear when we dive into it.

So our user story will be: we have an XML of a couple of person with there name and an attribute with there age, so you can simple use the classes from my previous examples. read more »

AS3 to Cocoa Touch: Array's

Posted in as3, cocoa touch, iphone, objective c on December 16th, 2008 by admin – 9 Comments

So for this topic I will discuss Array’s. So defined by wikipedia

“In computer science an array is a data structure consisting of a group of elements that are accessed by indexing. In most programming languages each element has the same data type and the array occupies a contiguous area of storage.”

So we all know that when we have an array in Actionscript we don’t have to fill it up with objects of the same data type’s, we can use any data type. We’re not restricted. That’s the same in Objective-C. Except 1 little thing. In objective-C if we want to fill up an array it can only be with Objects, not primitives (like int or float, ..). So what we will do is take a couple of examples using an Array in actionscript and converting it to Objective-c. Along the way we will se what is possible and what is not, or what will be different.

So first things first.

#Actionscript
var p1 : Person = new Person("john",15);
var string : String = new String("lol");
var number : Number = 15;
 
var array : Array = new Array(p1,string,number);
trace(array); //output: [object Person],lol,15
trace(array[2]); //output: 15

So what we have done is created 3 variables 1 object of the type Person ( see the previous example ). A simple string and a number. Create an Array and put those 3 variables in the array and trace it.

So how would we do that in Objective-c

#Objective-C
Person *p1 = [[Person alloc] initWithName:@"joe" andAge:34];
NSString *string = [NSString stringWithFormat:@"This is a string"];
NSNumber *number = [NSNumber numberWithInt:4];
 
NSArray *arr = [[NSArray alloc] initWithObjects:p1,string,number,nil];
NSLog(@"array : %@",arr);
NSLog(@"array object 2: %@",[mArr objectAtIndex:2]);

And our output should be:
2008-12-15 21:59:58.615 cocoatests[26361:20b] array : (
<Person: 0×524810>,
“This is a string”,
4
)
2008-12-15 21:59:58.615 cocoatests[26361:20b] array object 2: (
4
)

So what we do is exactly the same as in actionscript. Create 3 variables 1 of the type Person instantiate it with 2 parameters “joe” & 34 (as being a method defined in the interface of the Class Person ( if you want to know more about that or it is a little unclear just go back to my previous post about Objects and methods )) We make a String and A Number.

So for our “array part”. We make a new variables of the type NSArray  we allocate it to reserve space in the memory, and we immediately initialize it with some objects (being the objects created before). Doing this by using the method initWithObjects: followed by the objects we want to put in our array as a set of parameters. If you look closely enough you would see that we end our set of parameters with “nil”. This is because when we use initWithObjects, under the hood it iterates over every object until it finds nil so it knows it is at the end of the array. Everything that you put behind nil will not be pushed into your array.

So next on.. we want to add some more data to our array.

#Actionscript
array.push("foo");
array.push("bar");
array.push(12);
trace(array); //output: [object Person],lol,15,foo,bar,12

We us the push method to push new data in to our array (wich still can be of any datatype)

#Objective-C
So at our objective C side we cannot just add new data to an object of type NSArray, instead we have to use NSMutableArray. That’s because NSArray creates static arrays, and NSMutableArray creates dynamic arrays. Actually NSMutableArray is a subclass of NSArray wich adds extra functionality to NSArray such as push or remove new objects to our array.

So what we can do is create a new NSMutableArray or just push our already created array into our new NSMutableArray

#Objective-C
//Method 1
NSMutableArray *mArr = [[NSMutableArray alloc] initWithObjects:p1,string,number,nil];
 
//Method 2
NSMutableArray *mArr = [[NSMutableArray alloc] initWithArray:arr];
 
[mArr addObject:@"foo"];
[mArr addObject:@"bar"];
[mArr addObject:[NSNumber numberWithInt:15]];
 
NSLog(@"array : %@",mArr);

Which would result:
2008-12-15 22:24:26.883 cocoatests[26560:20b] array : (
<Person: 0×5229e0>,
“This is a string”,
4,
foo,
bar,
15
)

So what we have done is used the addObject method to add objects to our NSMutableArray. Simple as that. So for removing. We use the same principle only that in objective-c removing or replacing is better supported.

If we would like to remove the first object and the object called “foo” in actionscript we would do it like:

#Actionscript
array.splice(0,1);
array.splice(array.indexOf("foo"),1);
 
trace(array); //output: lol,15,bar,12
#Objective-C
[mArr removeObjectAtIndex:0];
[mArr removeObject:@"foo"];
 
NSLog(@"array : %@",mArr);

2008-12-15 22:39:14.451 cocoatests[26689:20b] array : (
“This is a string”,
4,
1,
15
)

if you want to know all the add/remove/replace function just go to NSMutableArray Reference
there you will find all the implementations.

So what about sorting ?

#Actionscript
var poets:Array = ["Blake", "cummings", "Angelou", "Dante"];
poets.sort(); // default sort
trace(poets); // output: Angelou,Blake,Dante,cummings
 
poets.sort(Array.CASEINSENSITIVE);
trace(poets); // output: Angelou,Blake,cummings,Dante
 
poets.sort(Array.DESCENDING | Array.CASEINSENSITIVE); // use two options
trace(poets); // output: Dante,cummings,Blake,Angelou

The Array class in Actionscript provides you with a couple of static constants that can be given as an argument to the sort method. It simply takes the array and sort it depending on the argument you pass it.

#Objective-C
NSArray *poets = [[NSArray alloc] initWithObjects:@"Blake",@"cummings",@"Angelou",@"Dante",nil];
 
NSLog(@"%@",[poets sortedArrayUsingSelector:@selector(compare:)]);
 
NSLog(@"%@",[poets sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]);
 
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:NO selector:@selector(caseInsensitiveCompare:)];
NSLog(@"%@",[poets sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]);

So this code creates exactly the same output as we would have in actionscript.

So for starters the sorting methods we use on the array doesn’t change the array itself as it does in actionscript but it returns a new array. What we can do is instantiate a new array. But for this example as I’m only showing the output of the array i skip that.

So if we look to the reference we see that the NSArray has a couple of methods to do sorting on. I’m going to discuss the 2 most used as from my experience.

The first one is the use of selectors (Selectors are used for method invocation) we use the method sortedArrayUsingSelector and we pass the selector we want to use by telling it is a selector @selector( <your selector > ).

The compare: selector is just going to sort it A-Z / 1-10 (and is defined in NSString, NSNumber..)
what gives the same result as the default sort method in actionscript.

If we wanted to use the caseInsesitiveCompare we just use that selector ( which is defined in NSString)

No for our next example being descending / caseInsensitive we are going to make use of Descriptors which are just separated objects that describe what sorting we want to take place on our array.

For that we use the NSSortDescriptor object. We allocate it you must initialize it with a key (I use nil because we don’t need a key) we pass the NO argument to ascending and we make us of a selector caseInsensitiveCompare like we did in our previous example. Now that our object is created we want to tell the array to sort on that descriptor we use the method sortedArrayUsingDescriptors (it expects an array so we put feed it an array created with our sortDescriptor object init). If we would log that you would see that it would result in a descending / caseInsensitive output.

So that was it for array’s for now. There is a lot more to cover, if you want to see something more clearly just leave a comment, or if something isn’t clear enough, let me know!

Next topic will be XML Parsing.

Cocoa touch for actionscript developers (basics)

Posted in as3, cocoa touch, iphone, objective c on December 4th, 2008 by admin – 18 Comments

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