The Nordhagen

  • Home
  • LazyFallback
  • BindMax
  • Olog
  • About me
Browsing: / Home
Shortlink

Objective-C for Flash Developers (pt. 2)

By Øyvind on Monday, March 26, 2012 in Objective-C, Programming
  • Part 1: Imports, strings and function calls
  • Part 2: Header files, variable and function definitions

In this part 2 of Objective-C for Flash developers, we will look at header files and how variables are defined in comparison to ActionScript 3. Before we start, I need to clarify one thing: I will consistently use the term function throughout this tutorial, although technically there is a semantic difference between funcitons and methods. It’s just to make this all easier on the brain, that’s all.

Header files (i.e. MyClass.h)

Any and all Objective-C classes are split into a .h file and a .m file. The former being the header file, the latter the implementation.

This is a concept that has no counterpart in AS3 so a direct comparison won’t be possible. What a header file does is list the definition of your class. In one way you could say that it’s a bit like the part you put before the constructor in you AS3 classes, in another you could say it’s like and AS3 interface. Both are correct to some extent, however neither would be accurate.

If you cmd+click the name of a framework class in the Xcode source editor, you will get to the class header file. In a way this is the Black Box Principle in practice; you get to see what the class exposes as it’s interface, but not how it does it’s grunt work. That is reserved for the implementation file. The one exeption to this is that a header file also defines any private properties of a class, so these are also exposed.

An Obj-C header file defines what instance variables, properties og functions a class has, which class it inherits from and the interfaces it adheres to. It is declared with the @interface keyword:

 Objective-C 
1
@interface MyClass : MySuperClass

@interface keyword, followed by class name, a colon and the super class name. For the most bare-bones objects, you extend NSObject.

You see, this might be the reason you would think a header file is like an AS3 interface, and it sort of is. But don’t put that one in the bank and move on just yet because you need to be aware that Objective-C has something called “protocols” which is semantically more similar to AS3 interfaces. We will deal with protocols in a later part, but for now here’s an illustration to help you map you understanding of these concepts to AS3:

In general you could say that the Objective-C header file is a combination of the AS3 class header and the AS3 interface, while the AS3 interface is a combination of the Objective-C header file and Objective-C protocols.

A complete abstract header file:

 Objective-C 
1
#import "SomeClass.h"
2
@class SomeOtherClass;
3
@interface MyClass : MySuperClass {
4
 DataType *myProtectedVariable;
5
}
6
 
7
@property (strong, nonatomic) DataType *propertyName;
8
-(void)doSomething;
9
@end

Now what’s all this? First of all, if you read part 1, you know that the #import keyword is just like imports in AS3. But here you see yet another kind of import:

@class imports

 Objective-C 
1
@class DetailViewController;

Quite simply, importing with @class does no more than tell the compiler that the class exists. This is called a forward declaration. The compiler will defer validation of the existance of the class to compile time. If your implementation uses properties or functions of this class, you will need to #import the class instead.

A way to remember which is which is to compare #import to ActionScript’s #include directive since that also uses the # sign and it inlines the code of the class. Another way is to notice that the @class keyword does not use a file extension (MyClass, not MyClass.h). This gives you an indication that @class is a general declaration, not an import.

Instance variables (ivars)

These are defined in what actually looks like a constructor, but this being a header file it’s not. (Actually, Obj-C doesn’t have explicit constructors, more on this in a later part).

 ActionScript 
1
protected var myProtectedVariable:DataType;

 Objective-C 
1
@interface MyClass : MySuperClass {
2
 DataType *myProtectedVariable;
3
}

Defining variables like this makes them local to the instance of the class. By default these variables are protected, making them accessible to the class and any subclasses, but not from the outside. Ivars can also be specified as private or public, though this is rare and highly discouraged.

Properties

 ActionScript 
1
// In an interface
2
function get propertyName():DataType
3
function set propertyName(value:DataType):void

 Objective-C 
1
@property (strong, nonatomic, readwrite) DataType *propertyName;

From left to right: @property keyword, property modifiers in parethesis (see below), the data type, which by C convention is always listed before the property/variable name, and lastly the propertyName, with or without the asterisk (see below).

A property is an externally accessible variable. It is not a public property and in the context of the header file it is merely a declaration stating to other classes that this is a property you can access. You will have to provide getter/setter implementations in the .m file to support this declaration. Think of it as declaring getter and setter functions in an AS3 interface.

Pointers

 Objective-C 
1
@property (strong, nonatomic, readwrite) DataType *propertyName;

You might have noticed that asterisk preceeding the property name. This declares that this variable is a pointer. A pointer is a reference to the memory space that an object occupies. By storing pointers to objects you don’t maintain copies of them throughout your application but rather references to the same instance.

Pointers do not have direct AS3 counterparts because AS3 is a higher level language that does not provide this level of memory management. In AS3 some datatypes are implicitly passed by reference/pointers (such as arrays) and others are passed by value, like strings. On a side note, in Objective-C strings are instances of NSString and as such they too are passed as pointers.

In Objective-C that asterisk is present whenever a pointer is declared, be it in a property, private variable or local variable. It is important to remember that function arguments are also declarations of local variables, hence you must include the asterisk there as well if the value you expect should be a pointer/reference.

Property modifiers

To assist in memory management, thread safety and access control, Objective-C has a number of possible modifiers you can specify in the property declaration. These are the words in parethesis following the @property keyword as seen in the example above:

 Objective-C 
1
@property (strong, nonatomic, readwrite) DataType *propertyName;

Regarding the memory modifiers, you should be aware that iOS 5 introduced automatic reference counting (ARC) which simplifies memory management and thus changed the list of possible modifiers. iOS Memory management and thread safety is beyond the scope of this post series. See Apple iOS Center documentation for these.

The access modifiers do have AS3 equivalents: Specifying readwrite is the same as implementing a getter and a setter, while readonly is the same as only implementing a getter.

Property modifiers can appear in any order. The default property modifiers are weak, atomic, readwrite and need not be specified.

Functions

In the example above you saw a function signature at its simplest:

 ActionScript 
1
public function doSomething():void

 Objective-C 
1
-(void)doSomething;

These are more appropriately called methods because they are exposed and as such part of the class interface. The minus sign denotes an instance method, as opposed to a static method which is prefixed by a + sign:

 ActionScript 
1
public static function doSomething():void

 Objective-C 
1
+(void) doSomething;

With arguments, functions look like this:

 ActionScript 
1
public function doSomething(soleArgument:DataType):void

 Objective-C 
1
-(void)doSomething: (DataType *) soleArgument;

That’s all nice and well. The asterisk pointer indicater is placed inside the data type declaration parenthesis. If this was a primitive value, like an integer, the asterisk would be omitted. Look at what happens when you include multiple arguments. In this case I wrote the example a little less abstract to better convey why this is:

 ActionScript 
1
public function doSomethingWith(myArgument:DataType, numRepetitions:int):void

 Objective-C 
1
-(void) doSomethingWithMyObject: (DataType *) theObject forThisManyTimes:(int) numRepetitions;

Whoah! That’s definitely not like ActionScript. Essentially you should read that signature like “do something with my object for this many times”. The function name and the first argument are together seen as the complete function name, whereas additional arguments add to it like a sentence. It sort of looks like you define the name of the second argument twice (and any additional arguments after that), but it’s actually not that weird. The name before the data type parethesis is the externally visible argument name (i.e. the name that pops up in the content assist), while the name after the parenthesis is the definition of the local variable exposed inside the function’s implementation.

What about return types? That’s easy:

 ActionScript 
1
public function getSomething():DataType

 Objective-C 
1
-(DataType) getSomething;

I’ll leave you with that for now :)

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Objective-C for Flash Developers (pt. 1)

By Øyvind on Friday, March 23, 2012 in Objective-C, Programming

  • Part 1: Imports, strings and function calls
  • Part 2: Header files, variable and function definitions

This will be a multipart blog post covering how to understand Objective-C in the ActionScript frame of reference. In this first part we will deal with imports, function calls and strings. I give you the AS3 to Obj-C transition guide, part 1.

Introduction

Coming from an AS2/AS3 background, I found that many of my conceptions of design patterns, event models and general application structure didn’t apply very well when starting out with Cocoa Touch and Objective-C. In fact I expected that because my choice to learn Objective-C in particular was with the intent of doing something very different from what I’m used to. I wanted to rip myself completely out of my comfort zone in an attemp to lower my natural resistance to anything new. I got what I bargained for, in spades.

Imports

I’ll start litterally at the top: Imports in AS3 and Objective-C are quite similar:

 ActionScript 3 
1
import somepackage.Class;

 Objective-C 
1
#import <Foundation/Foundation.h>
2
#import "Class.h"

Notice that the use of angle brackets is to denote a library of non-GUI classes and quotation marks to denote GUI classes. Notice also the lack of semicolons in import statements. The Obj-C Foundation classes are the basic framework for Objective-C, kind of like the playerglobal.swc in AS3, only in AS3 it’s a compiler argument and not an import in every single class file. It contains the basics like NSObject, NSArray and so on. In other words non-GUI classes, hence the angle brackets.

The UIKit is another Obj-C framework which, as you probably guessed by the UI prefix, is comprised of GUI-classes. It’s closest equivalent in AS3 would be the flash.display.* package. Being GUI-classes you import them like so:

 Objective-C 
1
#import "UIKit/UIKit.h"

Notice that the UIKit/Foundation/playerglobal analogy isn’t entirely accurate. playerglobal.swc includes both GUI and non-GUI classes, whereas in Objective-C they are separated.

Function/Method calls

This is the one thing that does the most in making Obj-C alien-looking to devs with an ECMAScript background. In Objective-C calling functions is not even called calling functions, but rather “passing messages”…that’s right: “passing messages”… I’ll let that sink in for a while because you’re gonna need it when you read forum threads and tutorials…”passing messages”.

So how do you pass a message?

 ActionScript 3 
1
myObject.myFunction();

 Objective-C 
1
[myObject myFunction];

…or rather “[myObject myMessage];”. You can use plain C code in Objective-C as well, in which case calling a function has the exact same syntax as in ActionScript. But Objective-C being a superset of C needs different syntax to differentiate itself from it’s ancestor (as with all adolescents).

Function calls with arguments

 ActionScript 3 
1
myObject.myFunction(soleArgument);

 Objective-C 
1
[myObject myFunction:soleArgument];

That last one is not something you have to get, it’s just syntax to memorize (and arguments is still called arguments in Obj-C). It gets harder when you have to deal with multiple arguments:
 ActionScript 3 
1
myObject.myFunction(firstArgument, secondArgument);

 Objective-C 
1
[myObject myFunction:firstArgument theSecondArgument:secondArgument];

Now hold on; that looks like two function calls in one! It’s not. In Objective-C you provide the argument label followed by the argument value for any arguments but the first one. Combined with the absence of a comma to separate the arguments, that it what makes it look like two function calls rather than one with two arguments. Actually if you did insert commas between the arguments, that would make them an array instead of an argument list.

This is one of the things Obj-C does to make itself more understandable, but it is also one of the things that make it seem like you need to be a fast typer in order to be productive in Objective-C. It gets clearer when you see it in the context of an actual example, here is how to initialize a standard iOS alert:

 Objective-C 
1
[myAlertInstance initWithTitle:@"My Alert" message:@"My message"
2
	delegate:self cancelButtonTitle:@"OK"];

You noticed that “@” sign preceeding those string literals didn’t you, and you wonder why? We’ll get to that shortly.

There’s no denying that this does make it easier to understand what the arguments are, but you will notice a somewhat odd tingle in the back of your spine the first few times you type it. Just remember: First argument has no label (usually the label is the last word in the camelcased function name), the others are of the form label:value with spaces in between them. Don’t worry. XCode’s code completion feature is really, really good and you don’t have to remember the labels for each function you use.

A word of caution: You might think that since the arguments are labeled that their order is optional, but this is not the case. However you will rarely be tempted to pass arguments in a different order than the function signature.

Function signatures are a page of it’s own, so we’ll deal with that next time. For now here is the lowdown on that “@” sign as promised.

Strings

 ActionScript 3 
1
foo = "bar";

 Objective-C 
1
foo = @"bar";

Again, this comes from the fact that Objective-C is a superset of C and it needs to not be like it’s parents. A C string literal is provided just like in ActionScript, that is why we say that AS is another C-based language. But usually in Objective-C we would like to use an instance of Obj-C’s own string object, NSString, because that gives us a whole bunch of helper methods to operate on it. Placing the “@” sign in front of the string literal does exactly that.

Next time we will deal with function signatures.

Trivia

  1. In C, a string is actually an array of characters, so you can probably imagine why NSString is preferable in a higher level language.
  2. An image in Objective-C is an instance of the UIImage class and the prefix “UI” naturally makes you think that it has to do with the user interface. You might even have assumed that it’s there because UIImage is part of UIKit (and you’d be right!). That’s all nice an logical, but what about the “NS” prefix, like in NSString and NSArray? This is derived from the fact that the first versions of OSX was actually called NeXTStep, made by the company NeXT, founded by Steve Jobs in the years he was outed from Apple.
Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

The case for BindMax for data binding

By Øyvind on Thursday, January 19, 2012 in Adobe Flash, BindLite, BindMax, Freebies


I made a couple of small updates to BindMax today (read about them at the bottom of the post). I’ve been using it myself for several projects and it has easily become one of my favorite self-made tools. It’s been been rock solid and serving me very well and I feel like more people should be using it. But maybe you don’t know what it improves upon? Let me help you.

Data binding is essentially tha synchonization of values, typically between the model and the views (read more here. For Flex applications data binding is typically accomplished with the [Bindable] compiler meta tag. For pure AS3 applications it’s been a roll-your-own world and some even use [Bindable] here as well. This is just wrong.

These are the reasons why BindMax is better than [Bindable]:

  • Mobile loving
    Building mobile apps with AIR? Then you know it’s all about squeezing file size out and performace in. BindMax is an implementation of the observer pattern, which is a much simpler structure than the Flash Event bus. In fact it’s beautiful minimalism compared the Events. Smaller file size, better performance.
  • Speed!
    For primitive data types BindMax is generally 3x faster than [Bindable]. Performance with complex data types obviously depends on how fast your compare functions are, if you have any. Without them, complex data types propagate just as fast as the primitve ones. The speed tests are included with the source so check for yourself!
  • Early type checking
    A data binding is usually defined early in the application run cycle. When that happens, BindMax will evaluate each attempt to bind a property or setter against the data type of the binding and throw an error if the data types don’t match. With [Bindable], you get no errors until the target property/setter for that binding is used. For a property that is used only rarely, you may never even see that error until the client/user stumbles over that rare use case and tells you.
  • Boot time property/getter/setter name validation on both sides of data binding
    Just as with type checking, BindMax validates that that the names match between the property or setter you bind a property or getter to.
  • Easy custom compare functions for complex and custom data types
    Primitive data type values like numbers and strings are easy to compare. Complex data types like arrays, dictionaries and custom objects require special handling. For this scenario, BindMax provides setCompareFunction which lets you pass it a function reference to a custom function that takes two instances of the same class and returns true if they are equal.
  • Optional automatic binding disposal
    To play nice with the garbage collector, BindMax lets you turn on automatic disposal of bindings which are no longer in use. When the last target for a binding is removed, BindMax will dispose of it.
  • Previous value retrieval
    BindMax stores the last value of each binding so you can retrieve it with retrieveLast if for comparison with the new value. The typical use case for this functionality is an animated image gallery where animation direction is determined based on image index vs previous image index. I’m sure you can think of several others.
  • Powerful reset function
    With the reset function, you can reset any or all of the bound properties to their default values (value of the property when the binding was defined). A quick call to reset followed by propagateAll will effectively reset you application.
  • Propagation forcing
    There are times when checking if a value is in fact changed simply doesn’t make sense. Then you wanna be sure that a value spreads to you application each time it is set, even if hasn’t changed. BindMax lets you override change detection on a per-update or per-property basis.

So go get it! At Google Code

NOTE: From now on I will be talking mostly about BindMax instead of it’s little brother BindLite. I’m leaving BindLite in the source in case someone finds it useful, but BindMax is much more verastile by not being an all static access class.

I’ve also updated the BindMax tutorial

The updates I made were the following:

  • Added reset all functionality when calling reset without arguments
  • Added setForcedPropagation function
  • Added propagateAll function
  • Removed outdated example project
Share this on: Mixx Delicious Digg Facebook Twitter
1 2 … 26 Next »

Search

Twitter

    Flickr

    Friends

    • Ballesparket
    • Christine Nygaard-Andersen
    • Haje’s Writings (Haje Jan Kamps)
    • Hastalasiesta (Martin Jacobsen)
    • Knut Nordhagen
    • Martin Jacobsen
    • Photocritic (Haje Jan Kamps)
    • The Montreal Twang (Thomas Wangsmo)

    Copyright © 2012 The Nordhagen.

    Powered by WordPress and News.