SlideShare ist ein Scribd-Unternehmen logo
1 von 46
iOS Application Development
Objective-C Basics
These are confidential sessions - please refrain from streaming, blogging, or taking pictures
Session 2
Vu Tran Lam
IAD-2013
• Objective-C introduction
• Creating your first Objective-C program
• Variables, data types and pointer
• Basic statements
• Conditions (if, switch)
• Loops (for, while, do... while)
• Primitives array
• Functions
• Exceptions
Today’s Topics
• Objective-C is the native programming language for Apple’s iOS
and OS X operating systems. It’s a compiled, general-purpose
language capable of building everything from command line utilities
to animated GUIs to domain-specific libraries.
Objective-C Introduction
• Like C++, Objective-C was designed to add object-oriented
features to C, but the two languages accomplished this using
fundamentally distinct philosophies.
• Objective-C is a strict superset of C, which means that it’s possible
to seamlessly combine both languages in the same source file.
Objective-C Introduction
• Launching Xcode
• Creating “Command Line Tool” project
• Declaring project info
• Run your program
Create Your First Objective-C Program
• Start Xcode and then select Create a New Xcode Project from the
startup screen.
Launching Xcode
• Choose OSX > Application > Command Line Tool project template.
Creating “Command Line Tool” Project
• Input product name, organisation name, company identifier and
type of framework.
Declaring Project Info
• Click on Run button on the tool bar to build and run your program.
Running Your Program
• Comments
• Data types
• Variables
• Operators
• Macros
• Typedef
• Structs
• Enums
• Pointers
Variables, Data Types and Pointer
• There are two ways to include commentary text in a C program.
Inline comments begin with a double slash (//) and terminate at the
end of the current line.
• Block comments can span multiple lines, but they must be
enclosed in /* and */ characters. For example:
// This is an inline comment
/* This is a block comment.
It can span multiple lines. */
Comment
Primitive data types
• void
• char
• (unsigned) short, int, long
• float, double
• BOOL (YES, NO, true, false)
Data Types
Reference data types
• NSString
• NSDecimal
• NSNumber
• NSSet
• NSArray
• NSDictionary
• id, Class, SEL
Primitive Data Types
Type Constant Examples NSLog Char
char ‘a’, ‘n’ %c
short int - %hi, %hx, %ho
unsigned short int - %hu, %hx, %ho
int 12, -97, 100U, 0xFFE0 %i, %d, %x
unsigned int 12u, 100U, 0XFFu %u, %x, %o
long int 12L, -2001, 0xfffL %li, %lx, %lo
unsigned long int 12UL, 100u1, 0xffeeUL %lu, %lx, %lo
long long int 0xe5e5e55L, 50011 %lli, %llx, %llo
unsigned long long int 12u11, 0xffeeULL %llu, %llx, %llo
float 12.34f, 3.1e-5f, 0x1.5p10, 0x1P-1 %f, %e, %g, %a
double 12.34, 3.1e-5, 0x.1p3 %f, %e, %g, %a
long double 12.34L, 3.1e-51 %lf, $le, %lg
id nil %p
• Variables are containers that can store different values. In C,
variables are statically typed, which means that you must explicitly
state what kind of value they will hold.
• To declare a variable, you use the <type> <name> syntax, and to
assign a value to it you use the = operator.
• If you need to interpret a variable as a different type, you can cast it
by prefixing it with the new type in parentheses.
Variables
#import <Foundation/Foundation.h>
!
int main(int argc, const char * argv[])
{
@autoreleasepool
{
char charType = 'A';
double doubleType = 9200.8;
// Casting double value to int value
int intType = (int)doubleType;
id idType = @"Hello World";
NSLog(@"Character value: %c", charType);
NSLog(@"Double value: %.1f", doubleType); // 9200.8
NSLog(@"Integer value: %d", intType); // 9200
NSLog(@"id value: %p", idType);
NSLog(@"id type description: %@", [idType description]);
}
return 0;
}
!
Variables Example
• The const variable modifier can be used to tell the compiler that a
variable is never allowed to change.
• For example, defining a constant called pi and then trying to alter it
will result in a compiler error:
double const pi = 3.14159;
pi = 42001.0; // Compile error
Constants
• Arithmetic operators (+, -, *, %, / )
• Relational operators (==, >, <, >=, <=)
• Logical operators (!, &&, ||)
• Assignment operator (=)
• Conditional operator (?)
Operators
• Arithmetic operators (+, -, *, %, / )
• Relational operators (==, >, <, >=, <=)
• Logical operators (!, &&, ||)
• Assignment operator (=)
• Conditional operator (?)
Operators
• Macros are a low-level way to define symbolic constants and
space-saving abbreviations.
• The #define directive maps a macro name to an expansion, which
is an arbitrary sequence of characters.
• Before the compiler tries to parse the code, the preprocessor
replaces all occurrences of the macro name with its expansion.
Macros
#import <Foundation/Foundation.h>
!
// Define macros
#define PI 3.14159
#define RAD_TO_DEG(radians) (radians * (180.0 / PI))
!
int main(int argc, const char * argv[])
{
@autoreleasepool
{
double angle = PI / 2; // 1.570795
NSLog(@"%f", RAD_TO_DEG(angle)); // 90.0
}
return 0;
}
Macros
• The typedef keyword lets you create new data types or redefine existing
ones.
• After typedef’ing an unsigned char in following example, we can use
ColorComponent just like we using char, int, double, or any other built-in
type:
#import <Foundation/Foundation.h>
!
typedef unsigned char ColorComponent;
!
int main(int argc, const char * argv[])
{
@autoreleasepool
{
ColorComponent red = 255;
ColorComponent green = 160;
ColorComponent blue = 0;
NSLog(@"Your paint job is (R: %hhu, G: %hhu, B: %hhu)", red, green, blue);
}
return 0;
}
Typedef
• A struct is like a simple, primitive C object. It lets you aggregate several
variables into a more complex data structure, but doesn’t provide any OOP
features (e.g., methods).
• For following example, allow you to create a struct to group the components
of an RGB color.
#import <Foundation/Foundation.h>
!
typedef struct
{
unsigned char red;
unsigned char green;
unsigned char blue;
} Color;
!
int main(int argc, const char * argv[])
{
@autoreleasepool
{
Color carColor = {255, 160, 0};
NSLog(@"Your paint job is (R: %hhu, G: %hhu, B: %hhu)", carColor.red,
carColor.green, carColor.blue);
}
return 0;
}
Structs
• The enum keyword is used to create an enumerated type, which is a
collection of related constants.
• Like structs, it’s often convenient to typedef enumerated types with a
descriptive name:
#import <Foundation/Foundation.h>
!
typedef struct
{
unsigned char red;
unsigned char green;
unsigned char blue;
} Color;
!
int main(int argc, const char * argv[])
{
@autoreleasepool
{
Color carColor = {255, 160, 0};
NSLog(@"Your paint job is (R: %hhu, G: %hhu, B: %hhu)", carColor.red,
carColor.green, carColor.blue);
}
return 0;
}
Enums
#import <Foundation/Foundation.h>
!
typedef enum
{
FORD,
HONDA,
NISSAN,
PORSCHE
} CarModel;
!
int main(int argc, const char * argv[])
{
@autoreleasepool
{
CarModel myCar = NISSAN;
switch (myCar)
{
case FORD:
case PORSCHE:
NSLog(@"You like Western cars?");
break;
case HONDA:
case NISSAN:
NSLog(@"You like Japanese cars?");
break;
default:
break;
}
}
return 0;
}
Enums
• A pointer is a direct reference to a memory address. Whereas a
variable acts as a transparent container for a value, pointers remove
a layer of abstraction and let you see how that value is stored. This
requires two new tools:
• The reference operator (&) returns the memory address of a normal variable.
• The dereference operator (*) returns the contents of a pointer’s memory
address.
// Define a normal variable
int year = 1967;
// Declare a pointer that points to an int
int *pointer;
// Find the memory address of the variable
pointer = &year;
// Dereference the address to get its value
NSLog(@"%d", *pointer);
// Assign a new value to the memory address
*pointer = 1990;
NSLog(@"%d", year);
Pointers
• The null pointer is a special kind of pointer that doesn’t point to
anything. There is only one null pointer in C, and it is referenced
through the NULL macro.
• This is useful for indicating empty variables something that is not
possible with a normal data type. For instance, the following snippet
shows how pointer can be “emptied” using the null pointer.
int year = 1967;
int *pointer = &year;
NSLog(@"%d", *pointer); // Do something with the value
pointer = NULL; // Then invalidate it
Null Pointers
• A void pointer is a generic type that can point to anything. It’s
essentially a reference to an arbitrary memory address.
• Accordingly, more information is required to interpret the contents of
a void pointer. The easiest way to do this is to simply cast it to a
non-void pointer.
• For example, the (int *) statement in the following code interprets the
contents of the void pointer as an int value.
int year = 1967;
void *genericPointer = &year;
int *intPointer = (int *)genericPointer;
NSLog(@"%d", *intPointer);
Void Pointers
• This is all good background knowledge, but for your Objective-C
development, you probably won’t need to use most of it.
• The only thing that you really have to understand is that all
Objective-C objects are referenced as pointers.
• For instance, an NSString object must be stored as a pointer, not a
normal variable:
NSString *anObject; // An Objective-C object
anObject = NULL; // This will work
anObject = nil; // But this is preferred
int *aPointer; // A plain old C pointer
aPointer = nil; // Don't do this
aPointer = NULL; // Do this instead
Pointers in Objective-C
• Basic statements
• Conditions (if, switch)
• Loops (for, while, do... while)
Basic Statements
• if statement
• switch statement
Conditional Statements
int modelYear = 1990;
if (modelYear < 1967)
{
NSLog(@"That car is an antique!!!");
}
else if (modelYear <= 1991)
{
NSLog(@"That car is a classic!");
}
else if (modelYear == 2013)
{
NSLog(@"That's a brand new car!");
}
else
{
NSLog(@"There's nothing special about that car.");
}
if Statement
// Switch statements (only work with integral types)
switch (modelYear)
{
case 1987:
NSLog(@"Your car is from 1987.");
break;
case 1988:
NSLog(@"Your car is from 1988.");
break;
case 1989:
case 1990:
NSLog(@"Your car is from 1989 or 1990.");
break;
default:
NSLog(@"I have no idea when your car was made.");
break;
}
switch Statement
• for
• while
• do..while
Loop Statements
int modelYear = 1990;
// While loop
int i = 0;
while (i<5)
{
if (i == 3)
{
NSLog(@"Aborting the while-loop");
break;
}
NSLog(@"Current year: %d", modelYear + i);
i++;
}
// For loop
for (int i=0; i<5; i++)
{
if (i == 3)
{
NSLog(@"Skipping a for-loop iteration");
continue;
}
NSLog(@"Current year: %d", modelYear + i);
}
Loops Statements
• Since Objective-C is a superset of C, it has access to the primitive arrays
found in C.
• Generally, the higher-level NSArray and NSMutableArray classes provided by
the Foundation Framework are much more convenient than C arrays;
however, primitive arrays can still prove useful for performance intensive
environments.
• Their syntax is as follows:
#import <Foundation/Foundation.h>
!
int main(int argc, const char * argv[])
{
@autoreleasepool
{
int years[4] = {1968, 1970, 1989, 1999};
years[0] = 1967;
for (int i = 0; i < 4; i++)
{
NSLog(@"The year at index %d is: %d", i, years[i]);
}
}
return 0;
}
Primitives Arrays
• Along with variables, conditionals, and loops, functions are one of
the fundamental components of any modern programming
language.
• They let you reuse an arbitrary block of code throughout your
application, which is necessary for organizing and maintaining all
but the most trivial code bases.
• Type of functions:
• Build-in functions (NSLog, NSMakeRange, CFCreateImage,…)
• User-defined functions
User-defined Functions
• Along with variables, conditionals, and loops, functions are one of
the fundamental components of any modern programming
language.
• They let you reuse an arbitrary block of code throughout your
application, which is necessary for organizing and maintaining all
but the most trivial code bases.
• Type of functions:
• Build-in functions (NSLog, NSMakeRange, CFCreateImage,…)
• User-defined functions
User-defined Functions
• Exceptions are represented by the NSException class. It’s designed
to be a universal way to encapsulate exception data, so you should
rarely need to subclass it or otherwise define a custom exception
object. NSException’s three main properties are listed below
Exceptions & Errors
Property Description
name An NSString that uniquely identifies the exception.
reason
An NSString that contains a human-readable
description of the exception.
userInfo
An NSDictionary whose key-value pairs contain extra
information about the exception. This varies based on
the type of exception.-
Exceptions
• Exceptions can be handled using the standard try-catch-finally
pattern found in most other high-level programming languages.
First, you need to place any code that might result in an exception
in an @try block. Then, if an exception is thrown, the corresponding
@catch() block is executed to handle the problem. The @finally
block is called afterwards, regardless of whether or not an
exception occurred.
• The following main.m file raises an exception by trying to access an
array element that doesn’t exist. In the @catch() block, we simply
display the exception details. The NSException *theException in the
parentheses defines the name of the variable containing the
exception object.
Handling Exceptions
#import <Foundation/Foundation.h>
!
int main(int argc, const char * argv[])
{
@autoreleasepool
{
NSArray *inventory = @[@"Honda Civic",
@"Nissan Versa",
@"Ford F-150"];
int selectedIndex = 3;
@try
{
NSString *car = inventory[selectedIndex];
NSLog(@"The selected car is: %@", car);
}
@catch(NSException *theException)
{
NSLog(@"An exception occurred: %@", theException.name);
NSLog(@"Here are some details: %@", theException.reason);
}
@finally
{
NSLog(@"Executing finally block");
}
}
return 0;
}
Handling Exceptions
• Cocoa predefines a number of generic exception names to identify
exceptions that you can handle in your own code. The generic
exception names are string constants defined in NSException.h
• NSGenericException
• NSRangeException
• NSInvalidArgumentException
• NSInternalInconsistencyException
• NSObjectInaccessibleException, NSObjectNotAvailableException
• NSDestinationInvalidException
• NSPortTimeoutException
• NSInvalidSendPortException, NSInvalidReceivePortException
• NSPortSendException, NSPortReceiveException
Predefined Exceptions
Documentation
Programming with Objective-C
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/
Introduction/Introduction.html
Exception Programming Topics
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Exceptions/Concepts/
PredefinedExceptions.html
many thanks
to
lamvt@fpt.com.vn
please
say
Stanford University
https://developer.apple.com
Developer Center
http://www.stanford.edu/class/cs193p
xin
chào
Next: Object Oriented Programming with
Objective-C - Part 1

Weitere ähnliche Inhalte

Was ist angesagt?

C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001Ralph Weber
 
Algebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain ModelsAlgebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
 
Architectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain ModelsArchitectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain ModelsDebasish Ghosh
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#ANURAG SINGH
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaKnoldus Inc.
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed worldDebasish Ghosh
 
CSharp for Unity Day 3
CSharp for Unity Day 3CSharp for Unity Day 3
CSharp for Unity Day 3Duong Thanh
 
Writing code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongWriting code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongVu Huy
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++Dmitri Nesteruk
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Gostrikr .
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersRichard Thomson
 
10. symbols | ES6 | JavaScript | TypeScript
10. symbols | ES6 | JavaScript | TypeScript10. symbols | ES6 | JavaScript | TypeScript
10. symbols | ES6 | JavaScript | TypeScriptpcnmtutorials
 
A fresh look at graphical editing
A fresh look at graphical editingA fresh look at graphical editing
A fresh look at graphical editingDr. Jan Köhnlein
 
2011 10-24-initiatives-tracker-launch-v1.0
2011 10-24-initiatives-tracker-launch-v1.02011 10-24-initiatives-tracker-launch-v1.0
2011 10-24-initiatives-tracker-launch-v1.0tommyoneill
 

Was ist angesagt? (20)

C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 
Algebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain ModelsAlgebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain Models
 
Architectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain ModelsArchitectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain Models
 
Javascript
JavascriptJavascript
Javascript
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
Java Performance MythBusters
Java Performance MythBustersJava Performance MythBusters
Java Performance MythBusters
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
CSharp for Unity Day 3
CSharp for Unity Day 3CSharp for Unity Day 3
CSharp for Unity Day 3
 
Writing code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongWriting code that writes code - Nguyen Luong
Writing code that writes code - Nguyen Luong
 
Automapper
AutomapperAutomapper
Automapper
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
 
AutoMapper
AutoMapperAutoMapper
AutoMapper
 
Scoping Tips and Tricks
Scoping Tips and TricksScoping Tips and Tricks
Scoping Tips and Tricks
 
Reflection in Go
Reflection in GoReflection in Go
Reflection in Go
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmers
 
10. symbols | ES6 | JavaScript | TypeScript
10. symbols | ES6 | JavaScript | TypeScript10. symbols | ES6 | JavaScript | TypeScript
10. symbols | ES6 | JavaScript | TypeScript
 
A fresh look at graphical editing
A fresh look at graphical editingA fresh look at graphical editing
A fresh look at graphical editing
 
2011 10-24-initiatives-tracker-launch-v1.0
2011 10-24-initiatives-tracker-launch-v1.02011 10-24-initiatives-tracker-launch-v1.0
2011 10-24-initiatives-tracker-launch-v1.0
 

Andere mochten auch

Session 15 - Working with Image, Scroll, Collection, Picker, and Web View
Session 15  - Working with Image, Scroll, Collection, Picker, and Web ViewSession 15  - Working with Image, Scroll, Collection, Picker, and Web View
Session 15 - Working with Image, Scroll, Collection, Picker, and Web ViewVu Tran Lam
 
Session 16 - Designing universal interface which used for iPad and iPhone
Session 16  -  Designing universal interface which used for iPad and iPhoneSession 16  -  Designing universal interface which used for iPad and iPhone
Session 16 - Designing universal interface which used for iPad and iPhoneVu Tran Lam
 
Session 4 - Object oriented programming with Objective-C (part 2)
Session 4  - Object oriented programming with Objective-C (part 2)Session 4  - Object oriented programming with Objective-C (part 2)
Session 4 - Object oriented programming with Objective-C (part 2)Vu Tran Lam
 
Succeed in Mobile career
Succeed in Mobile careerSucceed in Mobile career
Succeed in Mobile careerVu Tran Lam
 
Introduction to MVC in iPhone Development
Introduction to MVC in iPhone DevelopmentIntroduction to MVC in iPhone Development
Introduction to MVC in iPhone DevelopmentVu Tran Lam
 
Session 12 - Overview of taps, multitouch, and gestures
Session 12 - Overview of taps, multitouch, and gestures Session 12 - Overview of taps, multitouch, and gestures
Session 12 - Overview of taps, multitouch, and gestures Vu Tran Lam
 
Session 13 - Working with navigation and tab bar
Session 13 - Working with navigation and tab barSession 13 - Working with navigation and tab bar
Session 13 - Working with navigation and tab barVu Tran Lam
 
Session 14 - Working with table view and search bar
Session 14 - Working with table view and search barSession 14 - Working with table view and search bar
Session 14 - Working with table view and search barVu Tran Lam
 
Session 5 - Foundation framework
Session 5 - Foundation frameworkSession 5 - Foundation framework
Session 5 - Foundation frameworkVu Tran Lam
 
Session 8 - Xcode 5 and interface builder for iOS 7 application
Session 8 - Xcode 5 and interface builder for iOS 7 applicationSession 8 - Xcode 5 and interface builder for iOS 7 application
Session 8 - Xcode 5 and interface builder for iOS 7 applicationVu Tran Lam
 
Session 7 - Overview of the iOS7 app development architecture
Session 7 - Overview of the iOS7 app development architectureSession 7 - Overview of the iOS7 app development architecture
Session 7 - Overview of the iOS7 app development architectureVu Tran Lam
 
Session 1 - Introduction to iOS 7 and SDK
Session 1 -  Introduction to iOS 7 and SDKSession 1 -  Introduction to iOS 7 and SDK
Session 1 - Introduction to iOS 7 and SDKVu Tran Lam
 
Session 9-10 - UI/UX design for iOS 7 application
Session 9-10 - UI/UX design for iOS 7 applicationSession 9-10 - UI/UX design for iOS 7 application
Session 9-10 - UI/UX design for iOS 7 applicationVu Tran Lam
 
iOS design: a case study
iOS design: a case studyiOS design: a case study
iOS design: a case studyJohan Ronsse
 

Andere mochten auch (14)

Session 15 - Working with Image, Scroll, Collection, Picker, and Web View
Session 15  - Working with Image, Scroll, Collection, Picker, and Web ViewSession 15  - Working with Image, Scroll, Collection, Picker, and Web View
Session 15 - Working with Image, Scroll, Collection, Picker, and Web View
 
Session 16 - Designing universal interface which used for iPad and iPhone
Session 16  -  Designing universal interface which used for iPad and iPhoneSession 16  -  Designing universal interface which used for iPad and iPhone
Session 16 - Designing universal interface which used for iPad and iPhone
 
Session 4 - Object oriented programming with Objective-C (part 2)
Session 4  - Object oriented programming with Objective-C (part 2)Session 4  - Object oriented programming with Objective-C (part 2)
Session 4 - Object oriented programming with Objective-C (part 2)
 
Succeed in Mobile career
Succeed in Mobile careerSucceed in Mobile career
Succeed in Mobile career
 
Introduction to MVC in iPhone Development
Introduction to MVC in iPhone DevelopmentIntroduction to MVC in iPhone Development
Introduction to MVC in iPhone Development
 
Session 12 - Overview of taps, multitouch, and gestures
Session 12 - Overview of taps, multitouch, and gestures Session 12 - Overview of taps, multitouch, and gestures
Session 12 - Overview of taps, multitouch, and gestures
 
Session 13 - Working with navigation and tab bar
Session 13 - Working with navigation and tab barSession 13 - Working with navigation and tab bar
Session 13 - Working with navigation and tab bar
 
Session 14 - Working with table view and search bar
Session 14 - Working with table view and search barSession 14 - Working with table view and search bar
Session 14 - Working with table view and search bar
 
Session 5 - Foundation framework
Session 5 - Foundation frameworkSession 5 - Foundation framework
Session 5 - Foundation framework
 
Session 8 - Xcode 5 and interface builder for iOS 7 application
Session 8 - Xcode 5 and interface builder for iOS 7 applicationSession 8 - Xcode 5 and interface builder for iOS 7 application
Session 8 - Xcode 5 and interface builder for iOS 7 application
 
Session 7 - Overview of the iOS7 app development architecture
Session 7 - Overview of the iOS7 app development architectureSession 7 - Overview of the iOS7 app development architecture
Session 7 - Overview of the iOS7 app development architecture
 
Session 1 - Introduction to iOS 7 and SDK
Session 1 -  Introduction to iOS 7 and SDKSession 1 -  Introduction to iOS 7 and SDK
Session 1 - Introduction to iOS 7 and SDK
 
Session 9-10 - UI/UX design for iOS 7 application
Session 9-10 - UI/UX design for iOS 7 applicationSession 9-10 - UI/UX design for iOS 7 application
Session 9-10 - UI/UX design for iOS 7 application
 
iOS design: a case study
iOS design: a case studyiOS design: a case study
iOS design: a case study
 

Ähnlich wie Session 2 - Objective-C basics

(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-stringsNico Ludwig
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 developmentFisnik Doko
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2ndConnex
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...ANUSUYA S
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginnersophoeutsen2
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 

Ähnlich wie Session 2 - Objective-C basics (20)

C programming language
C programming languageC programming language
C programming language
 
(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings
 
C Programming
C ProgrammingC Programming
C Programming
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
Cpu
CpuCpu
Cpu
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
C
CC
C
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
C language
C languageC language
C language
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginner
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
Linked list
Linked listLinked list
Linked list
 
Aspdot
AspdotAspdot
Aspdot
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 

Mehr von Vu Tran Lam

iOS 7 Application Development Course
iOS 7 Application Development CourseiOS 7 Application Development Course
iOS 7 Application Development CourseVu Tran Lam
 
Android Application Development Course
Android Application Development Course Android Application Development Course
Android Application Development Course Vu Tran Lam
 
Your Second iPhone App - Code Listings
Your Second iPhone App - Code ListingsYour Second iPhone App - Code Listings
Your Second iPhone App - Code ListingsVu Tran Lam
 
Building a Completed iPhone App
Building a Completed iPhone AppBuilding a Completed iPhone App
Building a Completed iPhone AppVu Tran Lam
 
Introduction to iPhone Programming
Introduction to iPhone Programming Introduction to iPhone Programming
Introduction to iPhone Programming Vu Tran Lam
 
Responsive Web Design
Responsive Web DesignResponsive Web Design
Responsive Web DesignVu Tran Lam
 
HTML5 Web Standards
HTML5 Web StandardsHTML5 Web Standards
HTML5 Web StandardsVu Tran Lam
 
3D & Animation Effects Using CSS3 & jQuery
3D & Animation Effects Using CSS3 & jQuery3D & Animation Effects Using CSS3 & jQuery
3D & Animation Effects Using CSS3 & jQueryVu Tran Lam
 

Mehr von Vu Tran Lam (8)

iOS 7 Application Development Course
iOS 7 Application Development CourseiOS 7 Application Development Course
iOS 7 Application Development Course
 
Android Application Development Course
Android Application Development Course Android Application Development Course
Android Application Development Course
 
Your Second iPhone App - Code Listings
Your Second iPhone App - Code ListingsYour Second iPhone App - Code Listings
Your Second iPhone App - Code Listings
 
Building a Completed iPhone App
Building a Completed iPhone AppBuilding a Completed iPhone App
Building a Completed iPhone App
 
Introduction to iPhone Programming
Introduction to iPhone Programming Introduction to iPhone Programming
Introduction to iPhone Programming
 
Responsive Web Design
Responsive Web DesignResponsive Web Design
Responsive Web Design
 
HTML5 Web Standards
HTML5 Web StandardsHTML5 Web Standards
HTML5 Web Standards
 
3D & Animation Effects Using CSS3 & jQuery
3D & Animation Effects Using CSS3 & jQuery3D & Animation Effects Using CSS3 & jQuery
3D & Animation Effects Using CSS3 & jQuery
 

Kürzlich hochgeladen

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Kürzlich hochgeladen (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

Session 2 - Objective-C basics

  • 2. Objective-C Basics These are confidential sessions - please refrain from streaming, blogging, or taking pictures Session 2 Vu Tran Lam IAD-2013
  • 3. • Objective-C introduction • Creating your first Objective-C program • Variables, data types and pointer • Basic statements • Conditions (if, switch) • Loops (for, while, do... while) • Primitives array • Functions • Exceptions Today’s Topics
  • 4. • Objective-C is the native programming language for Apple’s iOS and OS X operating systems. It’s a compiled, general-purpose language capable of building everything from command line utilities to animated GUIs to domain-specific libraries. Objective-C Introduction
  • 5. • Like C++, Objective-C was designed to add object-oriented features to C, but the two languages accomplished this using fundamentally distinct philosophies. • Objective-C is a strict superset of C, which means that it’s possible to seamlessly combine both languages in the same source file. Objective-C Introduction
  • 6. • Launching Xcode • Creating “Command Line Tool” project • Declaring project info • Run your program Create Your First Objective-C Program
  • 7. • Start Xcode and then select Create a New Xcode Project from the startup screen. Launching Xcode
  • 8. • Choose OSX > Application > Command Line Tool project template. Creating “Command Line Tool” Project
  • 9. • Input product name, organisation name, company identifier and type of framework. Declaring Project Info
  • 10. • Click on Run button on the tool bar to build and run your program. Running Your Program
  • 11. • Comments • Data types • Variables • Operators • Macros • Typedef • Structs • Enums • Pointers Variables, Data Types and Pointer
  • 12. • There are two ways to include commentary text in a C program. Inline comments begin with a double slash (//) and terminate at the end of the current line. • Block comments can span multiple lines, but they must be enclosed in /* and */ characters. For example: // This is an inline comment /* This is a block comment. It can span multiple lines. */ Comment
  • 13. Primitive data types • void • char • (unsigned) short, int, long • float, double • BOOL (YES, NO, true, false) Data Types Reference data types • NSString • NSDecimal • NSNumber • NSSet • NSArray • NSDictionary • id, Class, SEL
  • 14. Primitive Data Types Type Constant Examples NSLog Char char ‘a’, ‘n’ %c short int - %hi, %hx, %ho unsigned short int - %hu, %hx, %ho int 12, -97, 100U, 0xFFE0 %i, %d, %x unsigned int 12u, 100U, 0XFFu %u, %x, %o long int 12L, -2001, 0xfffL %li, %lx, %lo unsigned long int 12UL, 100u1, 0xffeeUL %lu, %lx, %lo long long int 0xe5e5e55L, 50011 %lli, %llx, %llo unsigned long long int 12u11, 0xffeeULL %llu, %llx, %llo float 12.34f, 3.1e-5f, 0x1.5p10, 0x1P-1 %f, %e, %g, %a double 12.34, 3.1e-5, 0x.1p3 %f, %e, %g, %a long double 12.34L, 3.1e-51 %lf, $le, %lg id nil %p
  • 15. • Variables are containers that can store different values. In C, variables are statically typed, which means that you must explicitly state what kind of value they will hold. • To declare a variable, you use the <type> <name> syntax, and to assign a value to it you use the = operator. • If you need to interpret a variable as a different type, you can cast it by prefixing it with the new type in parentheses. Variables
  • 16. #import <Foundation/Foundation.h> ! int main(int argc, const char * argv[]) { @autoreleasepool { char charType = 'A'; double doubleType = 9200.8; // Casting double value to int value int intType = (int)doubleType; id idType = @"Hello World"; NSLog(@"Character value: %c", charType); NSLog(@"Double value: %.1f", doubleType); // 9200.8 NSLog(@"Integer value: %d", intType); // 9200 NSLog(@"id value: %p", idType); NSLog(@"id type description: %@", [idType description]); } return 0; } ! Variables Example
  • 17. • The const variable modifier can be used to tell the compiler that a variable is never allowed to change. • For example, defining a constant called pi and then trying to alter it will result in a compiler error: double const pi = 3.14159; pi = 42001.0; // Compile error Constants
  • 18. • Arithmetic operators (+, -, *, %, / ) • Relational operators (==, >, <, >=, <=) • Logical operators (!, &&, ||) • Assignment operator (=) • Conditional operator (?) Operators
  • 19. • Arithmetic operators (+, -, *, %, / ) • Relational operators (==, >, <, >=, <=) • Logical operators (!, &&, ||) • Assignment operator (=) • Conditional operator (?) Operators
  • 20. • Macros are a low-level way to define symbolic constants and space-saving abbreviations. • The #define directive maps a macro name to an expansion, which is an arbitrary sequence of characters. • Before the compiler tries to parse the code, the preprocessor replaces all occurrences of the macro name with its expansion. Macros
  • 21. #import <Foundation/Foundation.h> ! // Define macros #define PI 3.14159 #define RAD_TO_DEG(radians) (radians * (180.0 / PI)) ! int main(int argc, const char * argv[]) { @autoreleasepool { double angle = PI / 2; // 1.570795 NSLog(@"%f", RAD_TO_DEG(angle)); // 90.0 } return 0; } Macros
  • 22. • The typedef keyword lets you create new data types or redefine existing ones. • After typedef’ing an unsigned char in following example, we can use ColorComponent just like we using char, int, double, or any other built-in type: #import <Foundation/Foundation.h> ! typedef unsigned char ColorComponent; ! int main(int argc, const char * argv[]) { @autoreleasepool { ColorComponent red = 255; ColorComponent green = 160; ColorComponent blue = 0; NSLog(@"Your paint job is (R: %hhu, G: %hhu, B: %hhu)", red, green, blue); } return 0; } Typedef
  • 23. • A struct is like a simple, primitive C object. It lets you aggregate several variables into a more complex data structure, but doesn’t provide any OOP features (e.g., methods). • For following example, allow you to create a struct to group the components of an RGB color. #import <Foundation/Foundation.h> ! typedef struct { unsigned char red; unsigned char green; unsigned char blue; } Color; ! int main(int argc, const char * argv[]) { @autoreleasepool { Color carColor = {255, 160, 0}; NSLog(@"Your paint job is (R: %hhu, G: %hhu, B: %hhu)", carColor.red, carColor.green, carColor.blue); } return 0; } Structs
  • 24. • The enum keyword is used to create an enumerated type, which is a collection of related constants. • Like structs, it’s often convenient to typedef enumerated types with a descriptive name: #import <Foundation/Foundation.h> ! typedef struct { unsigned char red; unsigned char green; unsigned char blue; } Color; ! int main(int argc, const char * argv[]) { @autoreleasepool { Color carColor = {255, 160, 0}; NSLog(@"Your paint job is (R: %hhu, G: %hhu, B: %hhu)", carColor.red, carColor.green, carColor.blue); } return 0; } Enums
  • 25. #import <Foundation/Foundation.h> ! typedef enum { FORD, HONDA, NISSAN, PORSCHE } CarModel; ! int main(int argc, const char * argv[]) { @autoreleasepool { CarModel myCar = NISSAN; switch (myCar) { case FORD: case PORSCHE: NSLog(@"You like Western cars?"); break; case HONDA: case NISSAN: NSLog(@"You like Japanese cars?"); break; default: break; } } return 0; } Enums
  • 26. • A pointer is a direct reference to a memory address. Whereas a variable acts as a transparent container for a value, pointers remove a layer of abstraction and let you see how that value is stored. This requires two new tools: • The reference operator (&) returns the memory address of a normal variable. • The dereference operator (*) returns the contents of a pointer’s memory address. // Define a normal variable int year = 1967; // Declare a pointer that points to an int int *pointer; // Find the memory address of the variable pointer = &year; // Dereference the address to get its value NSLog(@"%d", *pointer); // Assign a new value to the memory address *pointer = 1990; NSLog(@"%d", year); Pointers
  • 27. • The null pointer is a special kind of pointer that doesn’t point to anything. There is only one null pointer in C, and it is referenced through the NULL macro. • This is useful for indicating empty variables something that is not possible with a normal data type. For instance, the following snippet shows how pointer can be “emptied” using the null pointer. int year = 1967; int *pointer = &year; NSLog(@"%d", *pointer); // Do something with the value pointer = NULL; // Then invalidate it Null Pointers
  • 28. • A void pointer is a generic type that can point to anything. It’s essentially a reference to an arbitrary memory address. • Accordingly, more information is required to interpret the contents of a void pointer. The easiest way to do this is to simply cast it to a non-void pointer. • For example, the (int *) statement in the following code interprets the contents of the void pointer as an int value. int year = 1967; void *genericPointer = &year; int *intPointer = (int *)genericPointer; NSLog(@"%d", *intPointer); Void Pointers
  • 29. • This is all good background knowledge, but for your Objective-C development, you probably won’t need to use most of it. • The only thing that you really have to understand is that all Objective-C objects are referenced as pointers. • For instance, an NSString object must be stored as a pointer, not a normal variable: NSString *anObject; // An Objective-C object anObject = NULL; // This will work anObject = nil; // But this is preferred int *aPointer; // A plain old C pointer aPointer = nil; // Don't do this aPointer = NULL; // Do this instead Pointers in Objective-C
  • 30. • Basic statements • Conditions (if, switch) • Loops (for, while, do... while) Basic Statements
  • 31. • if statement • switch statement Conditional Statements
  • 32. int modelYear = 1990; if (modelYear < 1967) { NSLog(@"That car is an antique!!!"); } else if (modelYear <= 1991) { NSLog(@"That car is a classic!"); } else if (modelYear == 2013) { NSLog(@"That's a brand new car!"); } else { NSLog(@"There's nothing special about that car."); } if Statement
  • 33. // Switch statements (only work with integral types) switch (modelYear) { case 1987: NSLog(@"Your car is from 1987."); break; case 1988: NSLog(@"Your car is from 1988."); break; case 1989: case 1990: NSLog(@"Your car is from 1989 or 1990."); break; default: NSLog(@"I have no idea when your car was made."); break; } switch Statement
  • 34. • for • while • do..while Loop Statements
  • 35. int modelYear = 1990; // While loop int i = 0; while (i<5) { if (i == 3) { NSLog(@"Aborting the while-loop"); break; } NSLog(@"Current year: %d", modelYear + i); i++; } // For loop for (int i=0; i<5; i++) { if (i == 3) { NSLog(@"Skipping a for-loop iteration"); continue; } NSLog(@"Current year: %d", modelYear + i); } Loops Statements
  • 36. • Since Objective-C is a superset of C, it has access to the primitive arrays found in C. • Generally, the higher-level NSArray and NSMutableArray classes provided by the Foundation Framework are much more convenient than C arrays; however, primitive arrays can still prove useful for performance intensive environments. • Their syntax is as follows: #import <Foundation/Foundation.h> ! int main(int argc, const char * argv[]) { @autoreleasepool { int years[4] = {1968, 1970, 1989, 1999}; years[0] = 1967; for (int i = 0; i < 4; i++) { NSLog(@"The year at index %d is: %d", i, years[i]); } } return 0; } Primitives Arrays
  • 37. • Along with variables, conditionals, and loops, functions are one of the fundamental components of any modern programming language. • They let you reuse an arbitrary block of code throughout your application, which is necessary for organizing and maintaining all but the most trivial code bases. • Type of functions: • Build-in functions (NSLog, NSMakeRange, CFCreateImage,…) • User-defined functions User-defined Functions
  • 38. • Along with variables, conditionals, and loops, functions are one of the fundamental components of any modern programming language. • They let you reuse an arbitrary block of code throughout your application, which is necessary for organizing and maintaining all but the most trivial code bases. • Type of functions: • Build-in functions (NSLog, NSMakeRange, CFCreateImage,…) • User-defined functions User-defined Functions
  • 39. • Exceptions are represented by the NSException class. It’s designed to be a universal way to encapsulate exception data, so you should rarely need to subclass it or otherwise define a custom exception object. NSException’s three main properties are listed below Exceptions & Errors Property Description name An NSString that uniquely identifies the exception. reason An NSString that contains a human-readable description of the exception. userInfo An NSDictionary whose key-value pairs contain extra information about the exception. This varies based on the type of exception.-
  • 41. • Exceptions can be handled using the standard try-catch-finally pattern found in most other high-level programming languages. First, you need to place any code that might result in an exception in an @try block. Then, if an exception is thrown, the corresponding @catch() block is executed to handle the problem. The @finally block is called afterwards, regardless of whether or not an exception occurred. • The following main.m file raises an exception by trying to access an array element that doesn’t exist. In the @catch() block, we simply display the exception details. The NSException *theException in the parentheses defines the name of the variable containing the exception object. Handling Exceptions
  • 42. #import <Foundation/Foundation.h> ! int main(int argc, const char * argv[]) { @autoreleasepool { NSArray *inventory = @[@"Honda Civic", @"Nissan Versa", @"Ford F-150"]; int selectedIndex = 3; @try { NSString *car = inventory[selectedIndex]; NSLog(@"The selected car is: %@", car); } @catch(NSException *theException) { NSLog(@"An exception occurred: %@", theException.name); NSLog(@"Here are some details: %@", theException.reason); } @finally { NSLog(@"Executing finally block"); } } return 0; } Handling Exceptions
  • 43. • Cocoa predefines a number of generic exception names to identify exceptions that you can handle in your own code. The generic exception names are string constants defined in NSException.h • NSGenericException • NSRangeException • NSInvalidArgumentException • NSInternalInconsistencyException • NSObjectInaccessibleException, NSObjectNotAvailableException • NSDestinationInvalidException • NSPortTimeoutException • NSInvalidSendPortException, NSInvalidReceivePortException • NSPortSendException, NSPortReceiveException Predefined Exceptions
  • 44. Documentation Programming with Objective-C https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/ Introduction/Introduction.html Exception Programming Topics https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Exceptions/Concepts/ PredefinedExceptions.html
  • 46. Next: Object Oriented Programming with Objective-C - Part 1