Toward iOS programming
Toward iOS programming
Overview Objective-C is an object oriented language. follows ANSI C style coding with methods
from Smalltalk
Flexible almost everything is done at runtime.Dynamic BindingDynamic TypingDynamic Linking
Inventors Objective-C was invented by two men,
Brad Cox and Tom Love. Both were introduced to Smalltalk at ITT in
1981 Cox thought something like Smalltalk
would be very useful to application developers
Cox modified a C compiler and by 1983 he had a working Object-oriented extension to C called OOPC.
Development
Tom Love acquired a commercial copy of Smalltalk-80 while working for Schlumberger Research
With direct access Smalltalk, Love added more to OOPC making the final product, Objective-C.
In 1986 they release Objective-C through their company “Stepstone”
NeXT and NeXTSTEP In 1988 Steve Jobs acquires Objective-
C license for NeXT Used Objective-C to build the
NeXTSTEP Operating System Objective-C made interface design for
NeXTSTEP much easier NeXTSTEP was derived from BSD Unix In 1995 NeXT gets full rights to
Objective-C from Stepstone
OPENSTEP API Developed in 1993 by NeXT and Sun An effort to make NeXTSTEP-like
Objective-C implementation available to other platforms.
In order to be OS independentRemoved dependency on Mach KernelMade low-level data into classes
Paved the way for Mac OS X, GNUstep
Apple and Mac OS X NeXT is taken over by Apple in 1996
and put Steve Jobs and his Objective-C libraries to work
Redesigned Mac OS to use objective-C similar to that of NeXTSTEP
Developed a collection of libraries named “Cocoa” to aid GUI development
Release Mac OS X (ten), which was radically different than OS 9, in March 2001
The Cocoa API Developed by Apple from NeXTSTEP and
OPENSTEP
Has a set of predefined classes and types such as NSnumber, NSstring, Nsdate, etc.
NS stands for NeXT-sun
Includes a root class NSObject where words like alloc, retain, and release come from
Dynamic Language
Almost everything is done at runtime
Uses dynamic typing, linking, and binding
This allows for greater flexibility
Minimizes RAM and CPU usage
To Import or Include?
C/C++’s #include will insert head.h into the code even if its been added before.
Obj-C’s #import checks if head.h has been imported beforehand.
#import “head.h”
Objective-C
Is a SUPERSET of C
Primitive data types from C int, short, long float,double char
Operators same as C
+ - * / ++ --
Address and Pointers
Same as C
To get address of a variable i
&i
Pointer
int *addressofi = &I;
Conditionals and Loops
Same as C/C++ if / else if/ else for while break ontinue do-while
for(int i=0; i< 22; i++) {
printf(“Checking i=“@d\n”, i); if(i+90 == i*i)
{ break;}}
for in loop
Introduced in Objective-C 2.0 (“fast enumeration”)
for(Item_Type *item in Collection_of_Items) {
//do whatever with the item Nslog(@” Looking now at %@”, item);}
Note: %@ in the NSLogconverts whatever is passed(in this case item) to a string
Functions
Same as C/C++ return_type functionName(type v1, type v2, ….) { //code of function
}
Examplevoid showMeInfo(int age){ printf(“You are %d years old”, age); //or use NSLog()}
Global and static variables
Same as C/C++ Global variables defined at top of file For static variables use keyword static before it
static in CurrentYear = 2013;
Functions --- pass by reference Same as C/C++return_type functionName(type v1, type *v2, ….) { //code of function
}
Example – call aboveint v1 = 2;int v2 = 3;functionName(v1, &v2);
Main Funciton –like C++#import <whatever/what.h>
int main(int argc, const char *argv[]){ @autoreleasepool { //your code here******* //you can have C code if you wish or Objective-C
return 0; }
}
NOTE: Latest version of Objective-C uses AutomaticReference Counting (kind of like automatic garbage collection)
----to handle getting rid of not needed items in memory (avoidingmemory leaks). YEAH! AUTOMATIC!
-----like Java this way
@autoreleasepool in a needed annotation around your mainblock of code to “enable” this
IMPORTANT --- we are doing iOS applications NOT mac OS applications
We will be doing iOS application that have a different framework called Model View Controller ----
But, for some examples to learn concepts of Objective-C we will show some basic main.m files with main functions that are not iOS programs!!!
We will learn iOS soon!
Main Function –like C++#import <whatever/what.h>
int main(int argc, const char *argv[]){ @autoreleasepool { //takes care of “automatic release of not needed items //static method date with no parameters is invoked on NSDate class
NSDate *now = [NSDate date]; //this will generate a new instance of NSDate with current time
NSLog(@”The new date lives at %p”, now); //Objective-C function that is like printf to console
double seconds = [now timeIntervalSince1970] //call timesInterrval* method on now object NSLog(@”It has been %f seconds since 1970”, seconds);
NSDate *later = [now dateByAddingTimeInterval:100000]; //pass 100000 parameter to method
NSLog(@”In 100,000 seconds will be %@”, later); //%@ means print as string
return 0; }}
Non-GUI – text output
Two standard functions you see used
printf() – same as C○ printf(“Hi Lynne”); //this is actual C code
NSLog()○ NSLog(@”Hi Lynne”); //this is strictly Objective-C
Classes
Have both definition file and implementation file : classname.h and classname.m
Similar to how have .h and .cpp in C++
Declaring a class in ClassName.h#import <Cocoa/Cocoa.h>
@interface ClassName : Parent {//class variables
int age;NSString name;
}// methods declared -(void)setAge:(int)number;-(void)setName:(NSString)n;-(int)getAge;-(NSString)getName;
@end
#import <standardimports.h>#import “local-your-otherfiles.h”
@interface ClassName: Parent { //class variables}
//methods-(return_type) methodName:(type)param1, (type) param2;
@end
Declaring methods
C++ syntax
Objective-C syntax
void function(int x, int y, char z);
Object.function(x, y, z);
-(void) method:(int)x, (int)y, (char)z;
[Object function:x, y, z];
-(return type) function_name: (type) p1, (type) p2, ***;Apply function to Objectpassing parameters x,y,z
Whats this + and – stuff? When declaring or implementing functions
for a class, they must begin with a + or - + indicates a “class method” that can only
be used by the class itself. (they are like static methods in Java invoked on class itself)
- indicates “instance methods” to be used by the client program (public functions) –invoked on an object / class instance . (they are like regular methods in Java invoked on object)
Class Implementation File (ClassName.m)#import “ClassName.h”@implementation ClassName
-(void)setAge:(int)number { age = number; }-(void)setName:(NSString)n { name = n; }-(int)getAge { return age; }-(NSString)getName { return name; }
@end
Remember our ClassName.h
#import <Cocoa/Cocoa.h>@interface ClassName : Parent {
//class variables int age;
NSString name; }// methods declared -(void)setAge:(int)number;-(void)setName:(NSString)n;-(int)getAge;-(NSString)getName;
@end
An example….the class Node
Class Declaration (Interface)#import <Cocoa/Cocoa.h>@interface Node : NSObject {
Node *link;int contents;
}+(id)new;-(void)setContent:(int)number;-(void)setLink:(Node*)next;-(int)getContent;-(Node*)getLink;@end
Node.h
Class is Node who’s parent is NSObject
{ class variables }
+/- private/public methods of Class
Class variables are private
Class Definition (Implementation)
#import “Node.h”@implementation Node+(id)new
{ return [Node alloc];}-(void)setContent:(int)number
{contents = number;}-(void)setLink:(Node*)next {
[link autorelease];link = [next retain];
}-(int)getContent
{return contents;}-(Node*)getLink
{return link;}@end
Node.m
Like your C++ .cpp file
>>just give the methods here
Creating class instances
ClassName *object = [[ClassName alloc] init];
ClassName *object = [[ClassName alloc] initWith* ]; NSString* myString = [[NSString alloc] init]; Nested method call. The first is the alloc method called on NSString itself.
This is a relatively low-level call which reserves memory and instantiates an object. The second is a call to init on the new object. The init implementation usually does basic setup, such as creating instance variables. The details of that are unknown to you as a client of the class. In some cases, you may use a different version of init which takes input:
ClassName *object = [ClassName method_to_create]; NSString* myString = [NSString string]; Some classes may define a special method that will in essence call alloc followed by
some kind of init
Creating an Object
Object ---invoking a method, the basics
Objective-C uses a Message Approach
Messages ---really weird (new) syntax Almost every object manipulation is done
by sending objects a message Two words within a set of brackets, the
object identifier and the message to send.
Like C++ or Java’s Identifier.message()
[Identifier message ]
Setting values for class variables of an object ---- THROUGH methods[object methodName];
[object setXXXMethod:value1];
[object setYYYYMethod:value2];
C++ VS. Objective-C Adds OOP,
metaprogramming and generic programming to C
Comes with a std library
Has numerous uses Large and complex
code for OOP
Only adds OOP to C Has no standard
library; is dependant on other libraries
Mostly used for application building
Simpler way of handling classes and objects
Keyword: id
The word ‘id’ indicates an identifier for an object much like a pointer in c++
This uses dynamic typing For example, if Pen is a class…
extern id Pen;
id myPen;
myPen = [Pen new ];
id work like pointers to objects.
Memory Allocation
Objects are created dynamically through the keyword, “alloc”
Objects are automatically deallocated in latest Objective-C through automatic reference counting
Automatic Reference Counting Objective C uses ‘AUTOMATIC reference
counting' as memory management
keeps an internal count of how many times an Object is 'needed'.
System makes sure that objects that are needed are not deleted, and when an object is not needed it is deleted.
iOS programs and @autoreleasepool You will notice (later when you learn)
your iOS applications are setup in Xcode (the IDE) with @autoreleasepool setup
This insures automatic release of unneeded items will take place for you.
linkList class#import "linkList.h"
@implementation linkList
+(id)new
{return [linkList alloc];}
-(void)insert:(int)value {
id temp = [Node new];
[temp setContent:value];
[temp setLink:head];
head = [temp retain];
[temp release];
}
-(void)append:(int)value { id last = [head getLink]; while ([last getLink] != nil) {last = [last getLink];} id temp = [Node new]; [temp setContent:value]; [last setLink:temp]; [temp release];}-(void)remove { id temp = head; head = [head getLink]; [temp release];}-(int)getValue { return [head getContent];}@end
linkList.m
Class linkList is child of previous Node class(not showing .h file for brevity)
Stack class (child of linkList)
#import "linkList.h”
@interface Stack : linkList
{}
+(id)new;
-(void)push:(int)value;
-(int)pop;
@end
#import "stack.h”
@implementation Stack+(id)new {return [Stack alloc];}
-(void)push:(int)value {[self insert:value];}
-(int)pop { int ret = [self getValue]; //getValue method of parent linkList [self remove]; //remove method of parent linkList return ret;}
@end
stack.h stack.m
self is like the C++/Java word this.
Remember alloc creates the object in memory
Example: main.m
#import "stack.h”int main(){
Stack *s = [Stack new];[s push:1];[s push:2];printf("%d\t", [s pop]);[s push:3];printf("%d\t", [s pop]);printf("%d\t", [s pop]);[s release]; return 0;
}
Run the program :
2 3 1
new is method defined in Stack class that simply that calls [Stack alloc]
--- done for convinience
Note only need to import “stack.h” because stack imports LinkList.h which imports Node.h which imports cocoa.h
release is method to release this object s explicitly from memory
Primitive data types
int, short, long float,double char
BOOL = means boolean
NSInteger and NSUnteger
NSInteger number; (Like long in C)NSUItneger another; (Like unsigned long in C)
Objective-C data types that are 32-Bits on 32-Bit platforms and 64-bits on 64-bit platforms
NSStringNSString *theMessage = @”hello world”;
Number of characters in a string○ NSUInteger charCount = [theMessage length];
Test if 2 strings equal○ if([string_var_1 isEqual: string_var_2])
{ //code for equal case }
String literal in Objective-C Begins with the @ symbol @”Lynne Grewe”;
Some Examples NSString *myString = @”Hello World”;
int len = [myString length];
ORint len = [@”Hello World” length];
OR
NSString *myString = [[NSString alloc] initWithString:@”Hello World”];
int len = [myString length];
This is like “Lynne Grewe” in most other languages
Formatting Strings in output NSLog
int a = 1;
float b = 33.22;
char c = ‘A’;
NSLog(@”Integer %d Float: %f Char: %c”, a, b, c);
NSString ---not changeable International (any language) strings using Unicode. Compiler will create an NSString for you using @“foo”
notation. An NSString instance can not be modified! They are
immutable. Usual usage pattern is to send a message to an NSString
and it will return you a new one. self.display.text = [self.display.text stringByAppendingString:digit]; self.display.text = [NSString stringWithFormat:@“%g”, brain.operand]; // class method
Tons of utility functions available (case conversion, URLs, substrings, type conversions, etc.).
Used throughout iOS instead of C language’s char * type.
NSMutableString ---changeable
Mutable version of NSString. Somewhat rarely used.
Can do some of the things NSString can do without creating a new one (i.e. in-place changes).
NSMutableString *ms = [[NSMutableString alloc] initWithString:@“0.”];
NSMutableString *ms = [NSMutableString stringWithString:@“0.”]; // inherited from NSString
[ms appendString:digit];
NSNumber
Object wrapper around primitive types like int, float, double, BOOL, etc.
NSNumber *num = [NSNumber numberWithInt:36];
float f = [num floatValue]; // would return 36 as a float (i.e. will convert types)
Useful when you want to put multiple numeric primitive types in a collection (e.g. NSArray or NSDictionary).
NSValue
Generic object wrapper for other non-object data types.
CGPoint point = CGPointMake(25.0, 15.0); // CGPoint is a C struct
NSValue *pointObject = [NSValue valueWithCGPoint:point];
NSData
“Bag of bits.” Used to save/restore/transmit data throughout the iOS SDK.
NSDate
“Used to find out the time right now or to store past or future times/dates.
See also NSCalendar, NSDateFormatter, NSDateComponents.
NSArray – holds fixed array of points to objectsNSArray *thearray = [NSArray arrayWithObjects:o1,o2,o3,o4, nil];
//get element[thearray objectAtIndex:0]; //element at index 0
Example
NSDate *now = [NSDate date];NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a dayNSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day
//array of DatesNSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday];
//get elements in arrayNSDate *first = [dateList objectAtIndex:0];
Methods are:count = gets number of items in arrayobjectAtIndex:i = returns element i of array (starting from 0)
Note: you can not add or remove a pointer from an NSArray---fixed once created
NSArray – cycle through with for loop
NSDate *now = [NSDate date];NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a dayNSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day
//array of DatesNSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday];
//get elements in arrayNSDate *first = [dateList objectAtIndex:0];
NSUInteger dateCount = [dateList count];for(int i=0; i<dateCount; i++) { NSDAte *d = [dateList objectAtIndex:i]; NSLog(@” Date is %@”, d); } Methods are:
count = gets number of items in arrayobjectAtIndex:i = returns element i of array (starting from 0)
NSArray – cycle through with for loop OPTION 2
NSDate *now = [NSDate date];NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a dayNSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day
//array of DatesNSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday];
//get elements in arrayNSDate *first = [dateList objectAtIndex:0];
For(NSDate *d in dateList) { NSDAte *d = [dateList objectAtIndex:i]; NSLog(@” Date is %@”, d); }
This is a “for in” loop --- convinient
NSMutableArray – changeable array of pointers to objects.NSMutableArray *thearray = [NSArray arrayWithObjects:o1,o2,o3,o4, nil];
//get element[thearray objectAtIndex:0]; //element at index 0
ExampleNSDate *now = [NSDate date];NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a dayNSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day
//array of DatesNSMutableArray *dateList = [NSMutableArray array];
//set elements[dateList addObject:now]; [dateList addObject:tomorrow];[dateList addObject:yesterday];
Methods are:array = gets empty NSMutableArrayaddObject:obj = adds as next element the obj to array
Note: you can add or remove a pointer from an NSMutableArray
NSMutableArray – adding element at Index location[arrayName insertObject:obj atIndex:i]
Example -- put in at beginning of array
[dateList insertObject:yesterday atIndex:0]
NSMutableArray – removing an element[arrayName removeObjectAtIndex:i]
Example
[dateList removeObjectAtIndex:0] //get rid of 1st element
NSDictionary Immutable hash table. Look up objects using a key to
get a value.+ (id)dictionaryWithObjects:(NSArray *)values forKeys:(NSArray *)keys;
+ (id)dictionaryWithObjectsAndKeys:(id)firstObject, ...;
Creation example:NSDictionary *base = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:2], @“binary”,
[NSNumber numberWithInt:16], @“hexadecimal”, nil];
Methods - (int)count; - (id)objectForKey:(id)key; - (NSArray *)allKeys; - (NSArray *)allValues;
see documentation (apple.com) for more details
NSMutableDictionary
Changeable+ (id)dictionaryWithObjects:(NSArray *)values forKeys:(NSArray *)keys;
+ (id)dictionaryWithObjectsAndKeys:(id)firstObject, ...;
Creation :+ (id)dictionary; //creates empty dictionary
Methods- (void)setObject:(id)anObject forKey:(id)key;
- (void)removeObjectForKey:(id)key;
- (void)removeAllObjects;
- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary;
see documentation (apple.com) for more details
NSMutableSet Changeable version of NSSet
Methods- (void)addObject:(id)anObject; // does nothing if object that isEqual:anObject is already in
- (void)removeObject:(id)anObject;
- (void)unionSet:(NSSet *)otherSet;
- (void)minusSet:(NSSet *)otherSet;
- (void)intersectSet:(NSSet *)otherSet;
see documentation (apple.com) for more details
Other useful Objective-C data classes NSOrderedSet, NSMutableOrderedSet
Cycling through Collections classes ---- use for-in loop
Example: NSArray of NSString
NSArray *myArray = ...;
for (NSString *string in myArray) { // no way for compiler to know what // myArray contains
double value = [string doubleValue]; // crash HERE if string not an NSString
}
NSSet example for-in loop
Example: NSSet of id
NSSet *mySet = ...;
for (id obj in mySet) { // do something with obj, but make sure you
//don’t send it a message it does not respond to
if ([obj isKindOfClass:[NSString class]]) {
// send NSString messages to obj with impunity
}
}
NSDictionary example for-in loop
Example: NSDictionary
NSDictionary *myDictionary = ...;
for (id key in myDictionary) {
// grab value associated with the current key
id value = [myDictionary objectForKey:key];
// do something with value here ***
}
Property list (plist) A collection of collections Specifically, it is any graph of objects containing only the following classes:
○ NSArray, NSDictionary, NSNumber, NSString, NSDate, NSData
Example1 : NSArray is a Property List if all its members are too --- NSArray of NSString is a Property List --- NSArray of NSArray as long as those NSArray’s members are Property Lists.
Example 2: NSDictionary is one only if all keys and values are too
Why define this term? Because the SDK has a number of methods which operate on Property Lists. Usually to read them from somewhere or write them out to somewhere. [plist writeToFile:(NSString *)path atomically:(BOOL)]; // plist is NSArray or NSDictionary
We will see this inpractice later
NSUserDefaults
Lightweight storage of Property Lists. an NSDictionary that persists between
launches of your application. Not a full-on database, so only store
small things like user preferences.
NSUserDefaults continued
Read and write via a shared instance obtained via class method standardUserDefaults
[[NSUserDefaults standardUserDefaults] setArray:rvArray forKey:@“RecentlyViewed”];
Methods (some)- (void)setDouble:(double)aDouble forKey:(NSString *)key;
- (NSInteger)integerForKey:(NSString *)key; // NSInteger is a typedef to 32 or 64 bit int
- (void)setObject:(id)obj forKey:(NSString *)key; // obj must be a Property List
- (NSArray *)arrayForKey:(NSString *)key; // will return nil if value for key is not NSArray
Always remember to write the defaults out after each batch of changes![[NSUserDefaults standardUserDefaults] synchronize];
CONCLUSION --- a note---Objective-C 2.0 – some features that were added In October 2007, Apple Inc. releases
Objective-C 2.0 for Mac OS 10.5 (Leopard)
Adds automatic garbage collection (ARC)
Instance Methods (public functions) are defined differently using