More On Variable, Categories and Protocols Chhorn Chhaly Leang Bunrong Cheng Udam Kan Vichhai Srou Chanthorn Em Vy Seth Sambo Chea Socheat
More On Variable,Categories and Protocols
Chhorn Chhaly
Leang Bunrong
Cheng Udam
Kan Vichhai
Srou Chanthorn
Em Vy
Seth Sambo
Chea Socheat
Content1. More on Variables and Data Types
Initialize Objects
Scoped Revisited More on properties, Synthesized Accessors, and Instance Variables
Global Variable
Static Variable
Enumerated Data Types
The typedef statement
Data Type Convers
• Categories and Protocols
Categories
Class Extensions
Protocols and Delegation
Composite Object
Initializing Objects
• We initializing object by calling “init” method
• For example Fraction *f=[[Fraction alloc]init];
• The example above we just get an Object that has nothing or field value
• If we want to initialize object with many fields value, we have to create our custom method to initialize object
Objective-C Java
Initializing Objects
• The method initWithNumerator:(int)n withDenominator:(int)d is the custom method to initializing object
• All initializing methods must start with word “init…..”
• Self=[super init] means the super class calls “init” method to initialize for current object
• But it just an object without any fields value
• After that line we see that we initialize _numerator and _denomitor
• Then we return “self” that fulfill of object with field values
Variable Scope
In Objective-C, a variable has been declared it may or may not be accessible to other sections of the program code. This accessibility depends on where and how the variable was declared and where the code is that needs to access it. This is know as variable scope.
Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only by statement that are inside that function or block of code. Local variable are not known to functions outside their own.Example:
Objective-C:-(void) sum:(int) x secondP:(int) y {
int total;total = x+y;NSLog(@”Total: %i”, total);
}NSLog(@”Total: %i”, total); // illegal Total is now out of scope.
Java:public void sum(int x, int y){
int total;total = x+y;System.out.println(“Total: ” + total);
}System.out.println(“Total: ”+ total); // illegal Total is now out of scope.
Global VariablesGlobal variables are defined outside of a function, usually on top of the program. A global variable can be accessed by any function. That is, a global variable is
Objective-C#import <Foundation/Foundation.h>Int myVar = 321;Int main (int argc, conts char * argv[]){ @autoreleasepool{
NSLog(@”myVar = %i”, myVar); } return 0;}
The second file, named display.m contain the code for the displayit() function.
#import <Foundation/Foundation.h>extern int myVar; void displayit(){ NSLog(@”MyVar from different source file is i%”, myVar);}
JavaPublic class Global{ Int myVar = 321; public static void main (String args[]){
System.out.println(“myVar = ”+ myVar);}
void displayit(){ System.out.println(“myVar = ”+myVar); }}
Multiple Classes In .h file In the Models.h file we declare two classes
Multiple Classes in .h file(cont.)
Import Models.h we get two classes
Accessing static and non static field to category Models class(.h.m)
Accessing static and non static field to category Calling static field(check) and non static field(modelsfield) to MyCatagory.
Enumerated Data Types
• Enumerated Type : Is an user-defined type that is used in Objective-C to represent the
data that can be stored in one of several predefined values (all of them are int).
• What is it’s purpose : The purpose of enumerated types is to create specifically named
constants.
• Syntax : enum name_of_enumerator { element1, element2,…};
• enum : tell compiler to create enumeration
• name_of_enum : is the name to be assigned the enumeration
• element: field are the name that can be used to set variable
Enumerated Data Types
NOTE : • enumerators use numbers corresponding to the element
• By default the first value corresponds to 0, the second to 1 and so on
• It is also possible to specify the values used by each value name
enum temperatureTypes{ cold = 10, // (redefined up = 10) warm, // down will 11 (increment one from
previous) hot = 95, // (redefined left = 95) veryhot // right will 96 (increment one from
previous) };
Example
The Typedef Statement
• The Typedef Statement : allows the programmer to define one Objective-C type as
another.
• To define a new typedef :
• Write the statement as if a variable of the original type was being declared
• Where you would put the name of the variable (after the type), place the new type name.
• Prefix everything with typedef
The Typedef Statement
• Syntax:
• Example:
in this example above, define the name Counter to be equivalent to the Objective-C data type int.
The second line we declare variable to be type of Counter.
typedef DataType variable;
typedef int Counter;
Counter i, j;
Data Type Conversion
• Type casting is a way to convert a variable from one data type to another data type.
• In Objective-C when we evaluation of the two operands, type of the result is convert to the big size between the two operands automatically but except char, short int or of an enumarated data type they are converted to int.
• Example: Output
• Example:Output
Data Type Conversion (cont.)
• In Objective-C is almost the same with Java but still have a little bit different below:
• In Java long and short are data type but in Objective-C is not so it make a conversion different.
In Java:In Objective-C:
Categories Category is the best way to add more methods to class in objective – C language.
We can override method in base class but it is poor programming practice( duplicate functionalities of method when running time).
Name of category start with base class plus category name( BaseClassName+CategoryName) in import section.
.m
.h
class
Category
Categories
Syntax:
@interface ClassName (CategoryName)
//// methods declaration part
@end
Categories
Cateories Example:
MyModel class has only one method (ownMethod).
CategoriesCateories Example:
CategoryOfMyModel has one method (newMethod).
CategoriesCateories Example:
MyModel
-(void)ownMethod-(void)newMethod
Compile time
MyModel
-(void)ownMethod
MyModel+CategoryModel
-(void)newMethod
Class Extensions
• Class extension is a special case allows creating a category without a name
- when you define an unnamed category like this, you can extend the class by adding
additional instance variables and properties.
- This is not allowed for named categories.
Class Extensions Cont......
MyClass.h
MyClass.m
Class Extensions Count......
Main method
Protocol• protocol fully complete abstraction every method in protocol is abstract
• it is list the method name without body, it wait other class implement it and implement body to it.
• we use it to create the standard method for all classes use the same method when they implement protocol, it is look like interface in java.
• and it use for delegate also
syntax in objective c syntax in java
Protocol
• in objective divided two part of protocol @required and @optional
• @required it mean that we need to implement method when the class implements it.
• @optional it mean that we are not need to implement method when the class implements it, it is up to you.
syntax:
Protocol
• we can implement more than one protocol
• how to implement single and multiple implement protocol
• first we need to import protocol
single implementation in objective c Single implementation in java
Protocol
multiple implementation in objective c multiple implementation in java
Delegate
• Delegate allow one object send message to other object when an event happen
• We use delegate almost for event handler in IOS
• We can use delegate when we want it to do something when something happen in our program and raise it up.
• We almost use id for create a delegate
• We will raise it detail in later chapter that detail about the delegate
Composite Object• What is composite object?
A technique that a class consists of one ore more objects from other classes is call “Composite Object”.
Diagram above show you that ClassA has ClassB as its composite.
If ClassA is deleted then ClassB is also deleted as a result. But if ClassB is deleted ClassA will not be delete.
ClassA ClassB
Composite Object
• Example of composite object:
Composite Object
• Let Create other Square class that have Rectangle as its composite
Composite Object
• In our main.m file
Composition Object
• Let compare our code with java code:
Rectangle.java
Composite Object• Square.java
Composite Object
• Main.java
Composite Object
• The result of these two will output the same
Thank you