Friday, August 28, 2009

iphone video

skin example part 2

@ set widht, height and skin in diff class
- (id)init {
if(self = [super init]) {
[self setBodyDef:new b2BodyDef];
[self setShapeDef:new b2PolygonDef];
[self setSize:CGSizeMake(64.0f, 64.0f)];
[self setHighlightedView:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ObstacleHighlighted.png"]] autorelease]];/// skin code by default
[self setNormalView:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ObstacleNormal.png"]] autorelease]];// skin at collision
return self;

Obstacle *anObstacle = [[[Obstacle alloc] init] autorelease];
[anObstacle setPosition:CGPointMake(60.0f, 130.0f)];
[anObstacle setRotation:45.0f];
[self addActor:anObstacle];


self :- self is simply a hidden parameter on every method. Like any other parameter, it receives its value from the function invocation.

When you type the following:
MyClass *myObject = [[MyClass alloc] initWithString:@"someString"];

The compiler converts this into function calls that look like this:
class myClass = objc_getClass("MyClass");
SEL allocSelector = @selector(alloc);
MyClass *myObject1 = objc_msgSend(myClass, allocSelector);

SEL initSelector = @selector(initWithString:);
MyClass *myObject2 = objc_msgSend(myObject1, initSelector, @"someString");

A method needs to know what data to act upon. The self parameter tells the class the data to act upon and so is essential to object oriented programming.

This statement may seem a little strange, since you can easily implement a method without using the self parameter by name. The reality is that the compiler uses the self parameter to resolve any reference to an instance variable inside a method.

If you had a class defined like this:
@interface MyClass : NSObject
NSInteger value;
- (void)setValueToZero;

///then the method:

- (void)setValueToZero
value = 0;
is converted by the compiler into:

void setValueToZero(id self, SEL _cmd)
self->value = 0;

So self is essential for accessing any instance variables, even if you never literally type "self".

Thursday, August 6, 2009