As you can see from the comments in Program 3.2, the program is logically divided into three sections:
The @interface section describes the class, its data components, and its methods, whereas the @implementation section contains the actual code that implements these methods. Finally, the program section contains the program code to carry out the in- tended purpose of the program.
Instance variables can be accessed from any instance method, but from nowhere else, including class methods.
unsigned int counter;Restricting the use of an integer variable to the exclusive storage of positive integers extends the accuracy of the integer variable.
The id data type is used to store an object of any type. In a sense, it is a generic object
type. It implies a pointer, so there's no need to type *id.
For example, this line declares number to be a variable of type id:
id number;
Methods can be declared to return values of type id, like so:
-(id) newObject: (int) type;
Type Cast
The type cast operator is often used to coerce an object that is a generic id type into an object of a particular class.
For example, the following lines convert the value of the id variable myNumber to a Fraction object:
id myNumber;
Fraction *myFraction;
…
myFraction = (Fraction *) myNumber;
The result of the conversion is assigned to the Fraction variable myFraction.
_Bool_Bool, for working with Boolean (that is, 0 or 1) values.
Objective-C programmers tend to use the BOOL data type instead of _Bool for working with Boolean values in their programs.This “data type” is actually not a data type unto it- self, but is another name for the char data type.This is done with the language’s special typedef keyword.
BOOL isPrime;
isPrime = YES;
or
isPrime = NO;
otherwise,
_Bool isPrime;
isPrime = true;
isPrime = false;
Apple's ObjetiveC's frameworks use BOOL.
Looping Constructs
int n, triangularNum;
for( n = 1 ; n <= 200; n++){
triangularNum += n;
}---------------
int n, triangularNum;
n = 1;
while (n<= 200) {
triangularNum += n;
n++;
}
----------------
int n, triangularNum;
n = 1;
do {
triangularNum += n;
n++;
} while (n <= 200);
Branching
if ( expression 1 )
program statement 1else if ( expression 2 )
program statement 2
else program statement 3
switch ( operator ) {
case ‘+’: [deskCalc add: value2];
break;
case ‘-’:
[deskCalc subtract: value2];
break;
case ‘*’:
[deskCalc multiply: value2];
break;
case ‘/’:
[deskCalc divide: value2];
break;
default:
NSLog (@”Unknown operator.”);
break;
}
Class Files
As in VB6, each class goes in it's own file:
Class.h -> @interface
Class.m -> @implementation
Automatic (synthesized) Accessor Methods
ObjetiveC 2.0 can automagically create accessor methods for an instance variable x called "x" and "setX". These methods are thread-safe.
In the implementation file ".h" mark the the variables with the @property directive and then apply the @synthesize directive to the same variables in the implementation module:
//
// Fraction.h
// FractionTest
//
// Created by Fernando Rodríguez Romero on 10/7/10.
// Copyright 2010 AGBO Business Architecture, SL. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Fraction : NSObject {
int numerator;
int denominator;
}
@property int numerator, denominator; (¡OJO! hay que repetir el tipo, en este caso un int)
-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
-(int) numerator;
-(int) denominator;
-(double) convertToNum;
@end//
// Fraction.m
// FractionTest
//
// Created by Fernando Rodríguez Romero on 10/7/10.
// Copyright 2010 AGBO Business Architecture, SL. All rights reserved.
//
#import "Fraction.h"
@implementation Fraction
@synthesize numerator, denominator;
-(void) print {
NSLog(@"%i/%i", numerator, denominator);
}
-(double) convertToNum {
if (denominator != 0) {
return (double) numerator / denominator;
}else {
return1.0;
}
}
@end
Dot syntactic sugar
[myFraction setNumerator: 1];
[myFraction denominator];
Here’s an equivalent way to write the same two lines:
myFraction.numerator = 1;
myFraction.denominator;
Messages with multiple arguments
Similar to Smalltalk:
-(void) setTo: (int) n over: (int) d;
-(void) setTo:(int)n over:(int)d {
numerator = n;
denominator = d;
}
Methods with no argument names
When creating the name for a method, the argument names are actually optional. For example, you can declare a method like this:
-(int) set: (int) n: (int) d;
This method is named set::, and the two colons mean the method takes two arguments, even though they’re not all named.
To invoke the set:: method, you use the colons as argument delimiters, as shown here:
[aFraction set: 1 : 3];
This is a bad thing.
Methods that take another object as a parameter
-(void) add: (Fraction *) aFraction;
Notice the asterisk: all references are actually pointers to objects.
¡OJO!
As the parameter is a pointer to an object, if the callee saves it and the caller later modifies it, it will change the state of the object!
All instances should OWN any object passed as a parameter in a method. You must therefore make a local copy of the parameter (are there methods for deep or shallow copy on NSObject?). You must also release this instance explicitly by overrinding the dealloc method of super.
Overriding the dealloc method and the keyword super
the release method only decreases the reference count of the object. If the refcount is zero, it deallocates the memory by sending the message dealloc.
You only overrride the method dealloc. Since dealloc returns an id, the overriding method should be:
-(id) dealloc {
if (ownedObject) {
[ownedObject release];
}
return [superdealloc];
}Static keyword
The static modifier has the same meaning as in vb6.
Self keyword
Same as in Smalltalk.
Methods that return objects
If a method returns an object, it is paramount that the caller releases the returned object!
-(Fraction *) add: (Fraction *) f
Maybe that's why some messages in the book return void instead of self (as in Smalltalk).
@class directive
The @class directive is a more efficient alternative to including a header file when we only need to mention a class, without ever using any of its methods. Not worth using it.
Constructors "a la Smalltalk"
Build them with class methods, just like in Smalltalk. However, it's common for their names to begin with "init".
//
// Complex.h
// FractionTest
//
// Created by Fernando Rodríguez Romero on 10/8/10.
// Copyright 2010 AGBO Business Architecture, SL. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Complex : NSObject {
doublereal;
doubleimaginary;
}
@property double real, imaginary;
-(void) print;
-(void) setReal: (double) a andImaginary: (double) b;
-(Complex *) add: (Complex *) f;