iOS - Presentation

advertisement
Titles
• Introduction to programming concepts
What is programming ?
Algorithms & Flowcharts
IDE & SDK
What we need ?
• Introduction to Objective-C
The history of Objective-C
Cocoa !
Variables & data types
How to use with X-Code console
Operators & Expressions
Loop statements : FOR, WHILE , DO WHILE
Flow Control statements: IF – ELSE
Functions
Introduction to Object Oriented Programming Concepts (OOP)
Why OOP?
What is a Class ?
What is an Object ?
Abstraction, Encapsulation , Inheritance , Polymorphisms
• Classes
Defining a Class
Ivars
Methods
Instantiation and Usage
Pointers
Introduction to Memory Management
Class Methods
Properties
• iOS Infrastructure
• Foundation Framework
NSString
NSArray
NSDictionary
NSSet
…
• MVC
Defining MVC
Developing our first iPhone App using MVC
Outlets & Actions
Simple Calculator
• UIKIT
UILabel
UIImage
UIButton
UIAlertView
…
• Protocols & Delegations
What is protocol?
Write a simple protocol.
What is the delegation ?
Using delegations
• Working with files
Reading & Writing Plist files
Working with other types
• Using TableView
• Using other Frameworks
What is programming ?
Computer programming is the process of designing, writing,
testing, debugging, and maintaining the source code of computer
programs.
What Is Algorithm?
An algorithm is a sequence of unambiguous instructions for solving a
problem, i.e., for obtaining a required output for any legitimate input in a finite
amount of time.
an example of an algorithm for sorting cards with colors on them into piles of
the same color:
1.
2.
3.
4.
5.
6.
Pick up all of the cards.
Pick a card from your hand and look at the color of the card.
If there is already a pile of cards of that color, put this card on that pile.
If there is no pile of cards of that color, make a new pile of just this card
color.
If there is still a card in your hand, go back to the second step.
If there is not still a card in your hand, then the cards are sorted. You are
done.
What Is Algorithm?
What Is Flowchart?
A flowchart is a type of diagram that
represents an algorithm or process, showing the
steps as boxes of various kinds, and their order by
connecting them with arrows.
IDE
An integrated development environment (IDE) is a software application that
provides comprehensive facilities to computer programmers for software
development. An IDE normally consists of a source code editor, build
automation tools and a debugger.
Some IDEs contain a compiler, interpreter, or both, such as Microsoft Visual
Studio and XCode; others do not, such as SharpDevelop and Lazarus.
SDK
A software development kit (SDK or "devkit") is typically a set
of software development tools that allows for the creation of
applications for a certain software package, software framework,
hardware platform, computer system, video game console,
operating system, or similar development platform.
What we need?
A Computer with MacOS Running
IDE : X-Code
Language : Objective – C & Swift
History of Objective-C
1972 - C programming language introduced
1980 – SmallTalk development leads to Objective-C in 1983
1988 – NeXTStep acquires license to Objective-C
1996 – Apple buys NeXT
2002 – OS X is built on Objective-C
2007/2008 – iPhone OS introduced with iPhone SDK
Variable
A variable is a storage location and an associated symbolic name (an identifier)
which contains some known or unknown quantity or information, a value. The
variable name is the usual way to reference the stored value
Data type
A data type or simply type is a classification identifying one of various types of
data, such as real-valued, integer or Boolean, that determines the possible
values for that type; the operations that can be done on values of that type; the
meaning of the data; and the way values of that type can be stored.
Type
Explanation
Type
same size as char, but
guaranteed to be signed.
char
smallest addressable unit of the
signed char
machine that can contain basic
character set. It is an integer type.
Actual type can be either signed or
unsigned char
unsigned depending on
implementation
short
short int
signed short
signed short int
short signed integer type. At least
16 bits in size.
unsigned short
unsigned short int
same as short, but
unsigned.
int
signed int
basic signed integer type. At least
16 bits in size.
unsigned
unsigned int
same as int, but unsigned.
long
long int
signed long
signed long int
long signed integer type. At least
32 bits in size.
unsigned long
unsigned long int
same as long, but unsigned.
long long
long long int
signed long long
signed long long
int
long long signed integer type. At unsigned long long
least 64 bits in size. Specified since unsigned long long
the C99 version of the standard.
int
float
(single precision) floating-point type
double
double precision floating-point type.
Explanation
same size as char, but
guaranteed to be unsigned.
same as long long, but
unsigned. Specified only in
C99 version of the
standard.
Variable
int someInteger = 42;
DataType
Variable name
float someFloatingPointNumber = 3.1415f;
double someDoublePrecisionFloatingPointNumber = 6.02214199e23;
bool flag = true;
Setting up the Debugger Console
The first thing to do whenever you start a debugging session is to open the
debugging console. You can open it by clicking this button on the main toolbar.
open Xcode preferences by pressing ⌘, or by going to the application menu
and selecting Xcode\Preferences. Click the Behaviors button (the button with
the gear over it).
NSLog Format
NSLog(@"%i",5);
%@ Object
%d, %i signed int
%u unsigned int
%f float/double
%1.2f to controll number of decimals
%x, %X hexadecimal int
%o octal int
%zu size_t
%p pointer
%e float/double (in scientific notation)
%g float/double (as %f or %e, depending on value)
%s C string (bytes)
%S C string (unichar)
%.*s Pascal string (requires two arguments, pass pstr[0] as the first, pstr+1 as the second)
%c character
%C unichar
%lld long long
%llu unsigned long long
%Lf long double
Data Type
NSLog(@"The
NSLog(@"The
NSLog(@"The
NSLog(@"The
NSLog(@"The
NSLog(@"The
NSLog(@"The
NSLog(@"The
NSLog(@"The
NSLog(@"The
NSLog(@"The
NSLog(@"The
size
size
size
size
size
size
size
size
size
size
size
size
of
of
of
of
of
of
of
of
of
of
of
of
NSLog(@"CHAR_MIN:
NSLog(@"CHAR_MAX:
NSLog(@"SHRT_MIN:
NSLog(@"SHRT_MAX:
NSLog(@"INT_MIN:
NSLog(@"INT_MAX:
NSLog(@"LONG_MIN:
NSLog(@"LONG_MAX:
NSLog(@"ULONG_MAX:
NSLog(@"LLONG_MIN:
NSLog(@"LLONG_MAX:
NSLog(@"ULLONG_MAX:
a char is: %li.", sizeof(char));
short is: %li.", sizeof(short));
int is: %li.", sizeof(int));
long is: %li.", sizeof(long));
long long is: %li.", sizeof(long long));
a unsigned char is: %li.", sizeof(unsigned char));
unsigned short is: %li.", sizeof(unsigned short));
unsigned int is: %li.", sizeof(unsigned int));
unsigned long is: %li.", sizeof(unsigned long));
unsigned long long is: %li.", sizeof(unsigned long long));
a float is: %li.", sizeof(float));
a double is %li.", sizeof(double));
%c",
%c",
%hi",
%hi",
%i",
%i",
%li",
%li",
%lu",
%lli",
%lli",
%llu",
CHAR_MIN);
CHAR_MAX);
SHRT_MIN);
SHRT_MAX);
INT_MIN);
INT_MAX);
LONG_MIN);
LONG_MAX);
ULONG_MAX);
LLONG_MIN);
LLONG_MAX);
ULLONG_MAX);
// signed short int
// signed long int
// unsigned long int
// signed long long int
// unsigned long long int
Comments
Comments in both programming and scripting languages provide a mechanism
for the developer to write notes that are ignored by the compiler or interpreter.
These notes are intended solely for either the developer or anyone else who
may later need to modify the code. The main purpose of comments, therefore,
is to allow the developer to make notes that help anyone who may read the
code later to understand issues such as how a particular section of a program
works, what a particular method does or what a variable is used to store.
Another useful application of comments in Objective-C is to comment out
sections of a program. Putting comment markers around sections of code
ensures that they are ignored by the compiler during compilation. This can be
especially useful when you are debugging a program and want to try out
something different, but do not want to have to delete the old code until you
have tested that the new code actually works.
Comments
Single Line Comments
// This is a comment line. It is for human use only and is ignored by the Objective-C compiler.
Multi-line Comments
/*
Multi Line
Comments
*/
Objective-C Expressions
The most basic expression consists of an operator, two operands and an
assignment. The following is an example of an expression:
int myresult = 1 + 2;
In the above example the (+) operator is used to add two operands (1 and 2)
together. The assignment operator (=) subsequently assigns the result of the
addition to an integer variable named myresult.
Arithmetic Operators
Operator
-(unary)
*
/
+
Description
Negates the value
of a variable or
expression
Operator
x += y
Add x to y and place result
in x
x -= y
Subtract y from x and
place result in x
x *= y
Multiply x by y and place
result in x
x /= y
Divide x by y and place
result in x
x %= y
Perform Modulo on x and
y and place result in x
x++
Increase value of variable
x by 1
x--
Decrease value of variable
x by 1
Multiplication
Division
Addition
-
Subtraction
%
Modulo
Description
Comparison Operators
Operator
Description
x == y
Returns true if x is equal to y
x>y
Returns true if x is greater than y
x >= y
Returns true if x is greater than or equal to y
x<y
Returns true if x is less than y
x <= y
Returns true if x is less than or equal to y
x != y
Returns true if x is not equal to y
Looping with the for Statement
for ( ''initializer''; ''conditional expression''; ''loop expression'' )
{
// statements to be executed
}
The initializer typically initializes a counter variable. Traditionally the variable
name i is used for this purpose, though any valid variable name will do. For
example:
i = 0;
int i=0;
for (i = 0; i < 100; i++)
{
// Statements here
}
Looping with the while Statement
The Objective-C for loop described previously works well when you know in
advance how many times a particular task needs to be repeated in a program.
There will, however, be instances where code needs to be repeated until a
certain condition is met, with no way of knowing in advance how many
repetitions are going to be needed to meet that criteria. To address this need,
Objective-C provides the while loop.
while (''condition'')
{
// Objective-C statements go here
}
Looping with the do ... while Statement
do
{
// Objective-C statements here
} while (''conditional expression'')
;
The do ... while loop, is provided for situations where you know that the code
contained in the body of the loop will always need to be executed at least once.
Flow Control with if and else
Since programming is largely an exercise in applying logic, much of the art of
programming involves writing code that makes decisions based on one or
more criteria. Such decisions define which code gets executed and, conversely,
which code gets by-passed when the program is executing. This is often
referred to as flow control since it controls the flow of program execution. The
if statement is perhaps the most basic of flow control options available to the
Objective-C programmer.
if (boolean expression) {
// Objective-C code to be performed when expression evaluates to true
}
Flow Control with if and else
if (boolean expression) {
// Code to be executed if expression is true
} else {
// Code to be executed if expression is false
}
if (boolean expression) {
// Code to be executed if expression is true
} else if (boolean expression) {
// Code to be executed if this expression is true and all last expressions are false
}
else
{
}
Function
What is a Function?
A function is a named block of code that can be called upon to perform a
specific task. It can be provided data on which to perform the task and is
capable of returning a result to the code that called it.
How to Declare an Objective-C Function ?
<return type> <function name> (<arg1 type> <arg1 name>, <arg2 type> <arg2 name>, ... )
{
// Function code
}
int multiply (int x, int y)
{
return x * y;
}
Function
Calling an Objective-C Function
int result;
result = multiply (10, 20);
int multiply (int x, int y)
{
return x * y;
}
Function
Functions need to be defined before they are used.
A function declaration tells the compiler what the function’s inputs and outputs
look like. By providing the data types for the return value and parameters of a
function, the compiler can make sure that you’re using it properly without
knowing what it actually does. The corresponding implementation attaches a
code block to the declared function. Together, these give you a complete
function definition.
// main.m
#import <Foundation/Foundation.h>
// Declaration
NSString *getRandomMake(NSArray *);
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSArray *makes = @[@"Honda", @"Ford", @"Nissan", @"Porsche"];
NSLog(@"Selected a %@", getRandomMake(makes));
}
return 0;
}
// Implementation
NSString *getRandomMake(NSArray *makes) {
int maximum = (int)[makes count];
int randomIndex = arc4random_uniform(maximum);
return makes[randomIndex];
}
Object Oriented Programming
Objective-C is known as an Object Oriented Programming (OOP)
language. OOP is a way of constructing software application composed of
objects. In other words, most of the code you’ve written in the app in
some ways deal with objects of some kind. UIViewController, UIButton,
UINavigationController and UITableView are some of the objects come
with the iOS SDK.
why OOP?
One important reason is that we want to decompose a complex software
into smaller pieces (or building block) which are easier to develop and
manage. Here, the smaller pieces are the objects. Each object has its own
responsibility and objects coordinate with each other in order to make the
software work.
Classes
• Classes provide the structure for objects
Define their prototype
• Classes define:
Set of attributes
Also called state
Represented by variables and properties
Behavior
Represented by methods
Class
Account
+Owner: Person
+Ammount: double
+suspend()
+deposit(sum:double)
+withdraw(sum:double)
Attributes
Operations
Objects
• Creating an object from a class is called instantiation
• An object is a concrete instance of a particular class
Object
• Objects have state
Set of values associated to their attributes
ivanAccount
• Example:
Class: Account
+Owner="Ivan Kolev"
+Ammount=5000.0
Objects: Ivan's account, Peter's account
Messages
•What is a message in OOP?
A request for an object to perform one of its operations (methods)
•All communication between objects is done via messages
Interfaces
•The interfaces provide abstractions
You shouldn't have to know anything about what is in the
implementation in order to use it (black box)
•An interface is a set of operations (methods) that given object can perform
Abstraction
•Abstraction is something we do every day
• Looking at an object, we see those things about it that have meaning
to us
• We abstract the properties of the object, and keep only what we need
•Allows us to represent a complex reality in terms of a simplified model
•Abstraction highlights the properties of an entity that we are most
interested in and hides the others
Inheritance
•A class can extend another class, inheriting all its data members and
methods
The child class can redefine some of the parent class's members and
methods and/or add its own
•A class can implement an interface, implementing all the specified
methods
•Inheritance implements the “is a” relationship between objects
Inheritance
Encapsulation
•Encapsulation means that all data members (fields) of a class are declared
private
Some methods may be private, too
•The class interacts with other classes (called the clients of this class) only
through the class’s constructors and public methods
•Constructors and public methods of a class serve as the interface to class’s
clients
Polymorphism
•A feature that allows 1 interface to be used for a general class of actions.
OOPs in Objective C
Objective-C is similar to C++ in that it abstracts a class’s interface from its
implementation. An interface declares the public properties and methods of
a class, and the corresponding implementation defines the code that actually
makes these properties and methods work.
Creating Classes
Xcode provides a convenient template
for creating new classes. To create our
class, navigate to File > New > File…
or use the Cmd+N shortcut. For the
template, choose Objective-C class
under the iOS > Cocoa Touch category.
After that, you’ll be presented with
some configuration options:
NSObject is Objective-C’s top-level class from which all others inherit.
Creating some sample classes
// Car.h
Protected instance variables
@interface Car : NSObject {
char Cartype;
int year;
int MaxSpeed;
}
- (void)drive;
@end
Methods
iVars
Protection Level
Compiler Directive
private
@private
protected
@protected
public
@public
package
@package
Description
The instance variable is accessible only within
the class that declares it.
The instance variables is accessible within the
class that declares it and any subclasses that
inherit it. This is the default protection method
for all instance variables declared in Objective-C
2.0.
The instance variable is accessible from any
other class or function.
The instance variable is accessible from any
other class or function inside of the package, i.e.
it is treated as though it were declared public, but
outside of the package it is treated as private.
This is actually useful for instance variables of
classes that are declared in libraries, SDK’s and
Frameworks.
Methods
Methods represent the actions that an object knows how to
perform.
1. Methods with no parameter
<method type>
(<return type>)
<method name>;
+ (void) doLogin;
- (void) doLogin;
Methods
2. Methods with a single parameter
<method type> (<return type>) <method name>: (<argument type>) <argument name>;
- (void) doLoginWithUserId: (NSString *) userId;
3. Methods with 2 parameters
<method type> (<return type>) <method name>: (<argument type>) <argument
name> <argument 2 label>: (<argument 2 type>) <argument 2 name>;
- (void) doLoginWithUserId: (NSString *) userId andPassword : (NSString *) pwd;
Class Methods
it is first important to explain the how these differ from instance
methods. Instance methods are essentially code routines that
perform tasks solely on instances of a class. In our BankAccount
example we created instance methods to get and set the bank
account number and bank balance instance variables and to
display the current values of those variables. Since each of
instance of the BankAccount class will have its own instance
variables containing corresponding instance specific values these
methods clearly only operate at the instance level of the class.
Class methods, on the other hand, work at the class level and are
common to all instances of a class.
Class Methods
UIColor
+ (UIColor *)blueColor;
+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue
alpha:(CGFloat)alpha;
NSURL
+ (id)URLWithString:(NSString *)URLString;
NSURLRequest
+ (id)requestWithURL:(NSURL *)theURL;
Creating some sample classes
// Car.h
@interface Car : NSObject {
char Cartype;
int year;
int MaxSpeed;
}
- (void)drive;
@end
// Car.m
#import "Car.h"
-(void)setYear : (int)CarYear
{
year = CarYear; //Setter
}
-(int)year
{
Return year; //getter
}
- (void)drive {
NSLog(@"Driving a %@. Vrooooom!", self.model);
}
@end
Creating more sample classes
Students , Rectangles , Computers
Pointers
When your code executes, that code resides in memory. Available to your code are two
types of memory: the stack and the heap. The stack, as its name implies, is a contiguous
block of memory. Values can be pushed into the stack and they can be popped off of the
stack. This mechanism is how functions are called: The parameters to a function are
pushed onto the stack and then execution resumes within the function where the
parameters are popped off the stack to make them available to the code within the
function.
Since the memory allocated for the
variable is set in the beginning itself,
we cannot use the stack in cases
where the amount of memory
required is not known in advance.
This motivates the need for HEAP
Pointers
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. This is
how you create pointers.
The dereference operator (*) returns the contents of a pointer’s memory address.
int year = 1967;
// Define a normal variable
int *pointer;
// Declare a pointer that points to an int
pointer = &year;
// Find the memory address of the variable
NSLog(@"%d", *pointer); // Dereference the address to get its value
*pointer = 1990;
// Assign a new value to the memory address
NSLog(@"%d", year);
// Access the value via the variable
Pointers
Pointers in Objective-C
This is all good background knowledge, but for your everyday 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 *model = @"Honda";
Classes
Instantiation and Usage
An object comes into runtime existence through a two-step process that allocates
memory for the object and sets its state to reasonable initial values. To allocate an
Objective-C object, send an alloc : message to the object’s class. The runtime allocates
memory for the object and returns a “raw” (uninitialized) instance of the class. It also
sets a pointer to the object’s class, zeros out all instance variables to appropriately
typed values, and sets the object’s retain count to 1.
After you allocate an object, you must initialize it. Initialization sets the instance
variables of an object to reasonable initial values. It can also allocate and prepare other
global resources needed by the object. You initialize an object by invoking an init
method or some other method whose name begins with init.
Classes
Instantiation and Usage
To call a method on an Objective-C object, you place the instance and the method in
square brackets, separated by a space. Arguments are passed after the method name,
preceded by a colon.
[toyota setModel:@”Toyota Corolla”]
getters and setters
Getter
Accessor method for getting the current value of the selected fields.
-(NSString*)firstName {
return firstName;
}
Setter
Mutator method for setting specified values to the selected fields.
-(void)setFirstName:(NSString*)newValue {
firstName = newValue;
}
A very brief to memory
managements
iOS and OS X applications accomplish object ownership, which
makes sure objects exist as long as they have to, but no longer.
We’ve been using the alloc method to create objects. But, it’s not
just allocating memory for the object, it’s also setting its
reference count to 1. This makes a lot of sense, since we wouldn’t
be creating the object if we didn’t want to keep it around for at
least a little while.
A very brief to memory
managements
This object-ownership scheme is implemented through a
reference-counting system that internally tracks how many
owners each object has. When you claim ownership of an object,
you increase it’s reference count, and when you’re done with the
object, you decrease its reference count. While its reference count
is greater than zero, an object is guaranteed to exist, but as soon
as the count reaches zero, the operating system is allowed to
destroy it.
A very brief to memory
managements
Garbage refers to objects, data, or other regions of the memory of
a computer system (or other system resources), which will not be
used in any future computation by the system, or by a program
running on it. As computer systems all have finite amounts of
memory, it is frequently necessary to deallocate garbage and
return it to the heap, or memory pool, so the underlying memory
can be reused.
Properties
An object’s properties let other objects inspect or change its state.
But, in a well-designed object-oriented program, it’s not possible
to directly access the internal state of an object. Instead, accessor
methods (getters and setters) are used as an abstraction for
interacting with the object’s underlying data.
Properties
The goal of the @property directive is to make it easy to create and configure
properties by automatically generating these accessor methods.
// Car.h
#import <Foundation/Foundation.h>
// Car.m
#import "Car.h"
@interface Car : NSObject
@implementation Car
@property BOOL running;
@synthesize running = _running;
Optional for Xcode 4.4+
@end
@end
The compiler generates a getter and a setter for the running property.
//
iOS Architecture
iOS Architecture
NSString
The NSString class is the basic tool for representing text in an Objective-C application.
Aside from providing an object-oriented wrapper for strings, NSString provides many
powerful methods for searching and manipulating its contents. It also comes with native
Unicode support.
Creating Strings
The most common way to create strings is using the literal @"Some String" syntax, but
the stringWithFormat: class method is also useful for generating strings that are
composed of variable values.
NSString *make = @"Porsche";
NSString *model = @"911";
int year = 1968;
NSString *message = [NSString stringWithFormat:@"That's a %@ %@ from
%d!",
make, model, year];
NSLog(@"%@", message);
NSString
Enumerating Strings
The two most basic NSString methods are length and characterAtIndex:, which return the
number of characters in the string and the character at a given index, respectively. You
probably won’t have to use these methods unless you’re doing low-level string
manipulation, but they’re still good to know
NSString *make = @"Porsche";
for (int i=0; i<[make length]; i++) {
unichar letter = [make characterAtIndex:i];
NSLog(@"%d: %hu", i, letter);
}
NSString
Comparing Strings
Instead of comparing pointers with the == operator, you should always use the
isEqualToString: method for a more robust value comparison.
NSString *car = @"Porsche Boxster";
if ([car isEqualToString:@"Porsche Boxster"]) {
NSLog(@"That car is a Porsche Boxster");
}
Combining Strings
The two methods presented below are a way to concatenate NSString objects.
NSString *car = [make stringByAppendingString:model];
NSLog(@"%@", car);
// Ferrari458 Spider
car = [make stringByAppendingFormat:@" %@", model];
NSLog(@"%@", car);
// Ferrari 458 Spider (note the space)
Foundation Framework
GCD & MultiThreading
NSData
NSCoding
NSData
NSCoding
Date Programming
Date Programming
NSDate
NSDateComponents
NSCalendar
NSDateFormatter
Exceptions & Errors
Exceptions
Handling Exceptions
Built-In Exceptions
Errors
Handling Errors
Categories
Whats is Categories
Creating Categories
Extensions
NSDate
NSDateComponents
NSCalendar
NSDateFormatter
Exceptions & Errors
Exceptions
Handling Exceptions
Built-In Exceptions
Errors
Handling Errors
Categories
Whats is Categories
Creating Categories
Extensions
KVC & KVO
KVC & KVO
KVC
KVO
KVC
KVO
Download