objective-c · 2019-02-03 · v a crucial difference between function calls and messages is that a...

69
OBJECTIVE-C A modern-person’s guide to iPhone code development:

Upload: others

Post on 23-Apr-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

OBJECTIVE-C

A modern-person’s

guide to iPhone code

development:

Page 2: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

YE OLDE PROGRAMMING LANGUAGES

C

Ruby

Objective C

C++

Smalltalk-80

Simula 67

Objective C 2.0

Java

Python

Perl

1983

1971

1980

1983

1987

1967 1991

1993

1995

2006

Source: Computer Languages Timeline * http://www.levenez.com/lang/

Page 3: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

WHAT IS OBJECTIVE-C?

v  AnobjectorientedlanguagewhichliesontopoftheClanguage.

v  Itsprimaryuseinmoderncompu;ngisonMacOSXasadesktoplanguageandalsooniPhoneOS(orasitisnowcalled:iOS).

v  ItwasoriginallythemainlanguageforNeXTSTEPOS,alsoknownastheopera;ngsystemAppleboughtanddescendedMacOSXfrom,whichexplainswhyitsprimaryhometodayliesonApple’sopera;ngsystems.

v  BecauseanycompilerofObjec;ve-CwillalsocompileanystraightCcodepassedintoit,wehaveallthepowerofCalongwiththepowerofobjectsprovidedbyObjec;ve-C.

Page 4: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

PRIMITIVES

v  TheusualCTypes•  int,float,...

v  It’sownboolean(ObjCforkedbeforeC99)•  BOOL•  TakesvaluesNO=0andYES=1

v  Somespecialtypes•  id,Class,SEL,IMP•  nilisusedinsteadofnull.

Page 5: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

STRINGS

v Always use (NSString *) instead of C Strings •  Inline :

@"Thisisaninlinestring";

•  Assigned:NSString*str=@"Thisisassignedtoavariable";

v  leaving out the @, causes a crash!

v Objective C Pointers aren’t abstracted, like java is. Look at

this, in the notes!

You must define constant strings this way, lest you

incite a programmic crash

Page 6: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

INTERFACE AND IMPLEMENTATION

v  A simple class in Objective-C , by default, has two files: v The implementation file which is a file that ends with a suffix of .m

v  The interface file which is a file that ends with a suffix of .h.

Page 7: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

CLASS DECLARATION

Page 8: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

INTERFACE

#import <COCOA Cocoa.h>     

@interface Person : NSObject {     

    //This is where attributes go      NSString *name;  NSNumber *age; NSString *address;

  }     //This is where methods go   - (void)updageAddress;      @end  

A system allowing for the declaration of clases and methods

Page 9: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

IMPORTING THE INTERFACE

v  The interface file must be included in any source module that

depends on the class interface

v  The interface is usually included with the #import directive.

Page 10: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

REFERRING TO OTHER CLASSES

v  An interface file declares a class and, by importing its superclass,

implicitly contains declarations for all inherited classes, from

NSObject on down through its superclass.

v  If the interface mentions classes not in this hierarchy, it must

import them explicitly or declare them with the @class

directive:

@class SyFy, FlyingMachine;

Page 11: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

IMPLEMENTATION

#import “Person.h"      @implementation Person    -(void) updateAddress {       

// code goes here to add gas   }     @end  

Page 12: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

MESSAGES

v Method Calling v. Message Passing v  In Objective-C, we call object methods by passing messages. v A message is sent to the instance v The message is the method we want to apply. v  Programmatically it looks like this:

[recipient message];

Page 13: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

v  With *No* arguments [object message];

[aPerson init];

v  With *1* Argument [object  message:value];

[aPerson initWithLast:@”Smith”];

v  With *2* arguments [object  message:value1 arg2:value2];

[aPerson initWithLast:@”Smith” andFirst:@”John”];

Page 14: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

MORE ON MESSAGES

v Messages can be sent to classes: [Person alloc];

v Messages can be nested: Person* p = [[Person alloc] initWithName:@”John”];

•  Equal to:Person* p = [Person alloc];[p initWithName:@”John”];

v  A crucial difference between function calls and messages is that a function and its

arguments are joined together in the compiled code, but a message and a receiving object aren’t united until the program is running and the message is sent.

v  Therefore, the exact method that’s invoked to respond to a message can only be determined at runtime, not when the code is compiled.

Page 15: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

METHOD DECLARATION

Page 16: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

METHODS

v Defineamethod:-(id)initWithFirst:(NSString*)firstName

andLast:(NSString*)lastName;-Callamethod:

[aPersoninitWithFirst:@”John” andLast:@”Smith”];

Page 17: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

CLASSEXAMPLES

v  NSString is a string of text that is immutable.

v  NSMutableString is a string of text that is mutable.

v  NSArray is an array of objects that is immutable.

v  NSMutableArray is an array of objects that is mutable.

v  NSNumber holds a numeric value.

v  If an object is immutable that means when we create the object and assign a value then it is static. The value can not be changed.

v  If an object is mutable then it is dynamic, meaning the value can be changed after creation.

Objective-C does not have syntax to mark classes as abstract, nor does it prevent you from creating an instance of an abstract class.

Page 18: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

OBJECTTYPING

•  Every object is of type

id

•  General type for any kind of object regardless of class

•  Can be used for both instances of a class and class objects themselves.

•  As a pointer to the instance data of the object.

id person; (dynamic typing)

•  Can declare a more specific type: Person* person; (static typing)

Page 19: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

TYPE INTROSPECTION

v  Instances can reveal their types at runtime.

v  isMemberOfClass: defined in the NSObject class, checks whether

the receiver is an instance of a particular class. if ( [anObject isMemberOfClass:someClass] )

v  isKindOfClass: checks more generally whether the receiver inherits

from or is a member of a particular class (whether it has the class

in its inheritance path): if ( [anObject isKindOfClass:someClass] )

Page 20: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

DYNAMICTYPING

v  The id type is completely nonrestrictive. By itself, it yields no information about an object, except that it is an object.

v  A program typically needs to find more specific information about the objects it contains.

v  Each object has to be able to supply it at runtime. v  The isa instance variable identifies the object’s class—what

kind of object it is. v  Objects with the same behavior (methods) and the same

kinds of data (instance variables) are members of the same class.

Page 21: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

EQUIVALENT STATEMENTS

v  Person *p = [[Person alloc] init];

v  id p= [[Person alloc] init];

Page 22: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

POINTERS AND INITIALIZATION

int main (int argc, const char * argv[]) {       NSString *testString;       testString = [[NSString alloc] init];       testString = @“This is a test string !";       NSLog(@"testString: %@", testString);       return 0;   

Page 23: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

CREATING INSTANCES

v Objec;ve-Chasalotofconven;onsthatarenotenforcedbythecompiler:

v Allocatesmemoryandreturnsapointer.

+(id)alloc;v Ini;alizesthenewlyallocatedobject.

-(id)init;Theallocmethoddynamicallyallocatesmemoryforthenew

object’sinstancevariablesandini;alizesthemallto0—all,thatis,excepttheisavariablethatconnectsthenewinstancetoitsclass.

Page 24: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

NSLOG COMMONSTR INGFORMATSPEC IF IERS

v  %@ Objec;ve-Cobjectusingthedescrip;onordescrip;onWithLocale:results

v  %% The“%”literalcharacter%dSignedinteger(32-bit)

v  %u Unsignedinteger(32-bit)

v  %f Floa;ng-point(64-bit)

v  %e Floa;ng-pointprintedusingexponen;al(scien;fic)nota;on(64-bit)

v  %c Unsignedchar(8-bit)

v  %C Unicodechar(16-bit)

v  %s Null-terminatedchararray(string,8-bit)

v  %S Null-terminatedUnicodechararray(16-bit)

v  %p Pointeraddressusinglowercasehexoutput,withaleading0x

v  %x Lowercaseunsignedhex(32-bit)

v  %X Uppercaseunsignedhex(32-bit)

Page 25: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

THE SCOPE OF INSTANCE VARIABLES

v @private•  Theinstancevariableisaccessibleonlywithintheclassthatdeclaresit.

v @protected–(default)•  Theinstancevariableisaccessiblewithintheclassthatdeclaresitandwithinclassesthatinheritit.

v @public•  Theinstancevariableisaccessibleeverywhere.

v @package•  Usingthemodernrun;me,an@packageinstancevariableactslike@publicinsidetheimagethatimplementstheclass,but@privateoutside.

v Bydefault,allunmarkedinstancevariablesare@protected.

Page 26: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

INIT IALIZ INGACLASS OBJECT

v Ifaclassmakesuseofsta;corglobalvariables,theini6alizemethodisagoodplacetosettheirini;alvalues.

+(void)ini;alize{ if(self==[ThisClassclass]){ //Performini;aliza;onhere....}} Becauseofinheritance,anini;alizemessagesenttoaclassthatdoesn’t

implementtheini;alizemethodisforwardedtothesuperclass,eventhoughthesuperclasshasalreadyreceivedtheini;alizemessage.

Page 27: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

CLASS NAMES IN SOURCE CODE

v Theclassnamecanbeusedasatypenameforakindofobject

Rectangle*anObject;v Asthereceiverinamessageexpression,theclassnamereferstotheclassobject

if([anObjectisKindOfClass:[Rectangleclass]])v  Ifyoudon’tknowtheclassnameatcompile;mebuthaveitasastringatrun;me,youcanuseNSClassFromStringtoreturntheclassobject:

NSString*className;...if([anObjectisKindOfClass:NSClassFromString(className)])

v Youcantesttwoclassobjectsforequalityusingadirectpointercomparison.

if([objectAclass]==[objectBclass]){//...

Page 28: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

VARIABLES ANDCLASSOBJECTS v  Foralltheinstancesofaclasstosharedata:v  Thesimplestwaytodothisistodeclareavariableintheclassimplementa;onfile:

intMCLSGlobalVariable;@implementa;onMyClass

v  Inamoresophis;catedimplementa;on,declareavariabletobesta;c,andprovideclassmethodstomanageit.

v  Declaringavariablesta;climitsitsscopetojusttheclass—andtojustthepartoftheclassthat’simplementedinthefile.

v  Unlikeinstancevariables,sta;cvariablescannotbeinheritedby,ordirectlymanipulatedby,subclasses.

Page 29: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

PROPERTYANDSYNTHESIZE

@interfacePerson:NSObject{

//ThisiswhereaoributesgoNSString*name;NSNumber*age;NSString*address;

}@end

TheseallneedSeoersandGeoers

Page 30: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

@interfacePerson:NSObject{

//ThisiswhereaoributesgoNSString*name;NSNumber*age;NSString*address;

}@property(readwrite,retain)NSString*name;@property(readwrite,retain)NSString*address@property(readwrite,retain)NSNumber*age;

@end

v  Thinkofapropertyasacompilermacrothatgeneratethegeoerandseoerforyou.

Page 31: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

@implementa;onPerson@synthesizename,age,address;…}@endv @propertyreplacesalloftheinterfacemethoddeclara;onsforgeoersandseoers,v @synthesizereplacestheactualmethodsthemselves.

Page 32: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

PROPERTY ATTRIBUTES @property(readonly)intkey;@property(nonatomic,retain)NSString*;tle;@property(nonatomic,copy)NSString*first_name; Format:@property(aKributes)typename;

Writabilityreadwrite(default)readonly

SeKerSemanQcsassign(default)retaincopyAtomicitynonatomic(no“atomic”aoributebutthisisthedefault)

Source:

hop://developer.apple.com/documenta;on/Cocoa/Conceptual/Objec;veC/Ar;cles/chapter_5_sec;on_3.html

Page 33: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

CALLINGPROPERTIES

@property(nonatomic,copy)NSString*name;Use“dotnota;on”: person.name=@”JohnSmith";

a=person.name;OrMessagepassing:

[personsetName:@”JohnSmith"]; a=[persongetName];

Page 34: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

USING DOT SYNTAX

•  Use dot syntax to invoke accessor methods using the same pattern as accessing structure elements.

myInstance.value = 10; –  which is equivalent to:

[myInstance setValue:10];

•  You can read and write properties using the dot (.) operator

•  Accessing a property property calls the get method associated with the property (by default, property)

•  Setting it calls the set method associated with the property (by default, setProperty:).

•  An advantage of the dot syntax is that the compiler can signal an error when it detects a write to a

read-only property, whereas at best it can only generate an undeclared method warning that you

invoked a non-existent setProperty: method, which will fail at runtime.

•  There is one case where properties cannot be used:

id y; x = y.z; // z is an undeclared property

Page 35: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

•  If you want to access a property of self using accessor methods, you must explicitly call

out self as illustrated in this example: self.age = 10;

•  If you do not use self., you access the instance variable directly.

•  In the following example, the set accessor method for the age property is not invoked: age = 10;

•  If a nil value is encountered during property traversal, the result is the same as sending

the equivalent message to nil.

Page 36: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

MEMORYMANAGEMENT

v  InObjec;ve-Ctherearetwomethodsformanagingmemory:•  Referencecoun;ng--Manual–

•  dependsoncodeaddedbytheprogrammer

•  Garbagecollec;on.--Automa;c–•  systemautoma;callymanagingthememory.–•  NotavailableoniPhone.

Page 37: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

Op:

+1 +1 -1 -1RefCount

1 0 1 2 1

+alloc -init -retain -release -release

main() Create array Release from use

my_func() Retain for use

initialize

Release from use

OBJECT LIFECYCLE

Page 38: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

AUTORELEASE AND AUTORELEASE POOLS

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];     [pool drain];  

v  When the autorelease message is sent to an object, that object is then added to the inner most auto release pool

v  When the pool is sent the drain ( i.e. release) message, then all the objects sent the autorelease message are released

v  Autorelease defers the release until later. v  You may nest as many autorelease pools as you need. v  The inner autorelease pool has absolutely no effect on the outer

autorelease pool

Page 39: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

RETAINCOUNT

v  Amethodwecanusetoseehowmanyreferencesanobjecthas.

v  Canbeusedasfollows:NSLog(@"retainCount for person: %d", [person retainCount]);  

v  Noneedtopaytoomuchaoen;ontoretainCount,bestprac;ce:v Whenyouwantanobject,retain(oralloc)it.v Whenyouaredonewithanobject,releaseit.

Page 40: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

WHEN IS AN OBJECT DESTROYED?

v  When it’s retain count reaches 0, then the deconstructor - dealloc is called

v  Never call dealloc yourself -- this is always called automatically for you.

v  (Except when you’re calling [super dealloc] from within your dealloc implementation)

-(void)dealloc {

[super dealloc];[name release]; [address release];

}

Page 41: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

PROTOCOLS

v  Aprotocoldeclaresmethodsthatcanbeimplementedbyany

class.

v  Protocolsarenotclassesthemselves.

v  Theysimplydefineaninterfacethatotherobjectsare

responsibleforimplemen;ng.

v Whenyouimplementthemethodsofaprotocolinoneofyour

classes,yourclassissaidtoconformtothatprotocol.

Page 42: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

@protocol MyProtocol

- (void)myProtocolMethod;

@end

v  protocolsdonothaveaparentclass

v  theydonotdefineinstancevariables@interface MyClass : NSObject <UIApplicationDelegate, MyProtocol > {

}

@end

v  Protocolmethodscanbemarkedasop;onalusingthe@op;onalkeyword.Orrequiredusing@requiredkeywordtoformallydenotetheseman;csofthedefaultbehavior.

v  Thedefaultis@required,ifnokeywordisspecified.

Page 43: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

CATEGORIES

v  Allowustoaddmethodstoanexis;ngclass,sothatall

instancesofthatclassintheapplica;ongaintheadded

func;onality.

v  Theyaredifferentfromsubclassing

v  Categoriesdon’tallowyoutouseinstancevariables.

v  itispossibletooverwriteamethodalreadyinplace

Page 44: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

CATEGORY SYNTAX

@interface ClassNameHere (category)   

   // method declaration(s)     

@end     The implementation looks like this;      

@implementation ClassNameHere (category)     

// method implementation(s)     

@end  File naming convention following the pattern of the name of the class we are adding a category to, a plus sign, and the name of our category.

Page 45: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

C A TE G ORY E XA MPL E

@interface NSString (reverse)     

-(NSString *) reverseString;   @end  

For the implementation:

@implementation NSString (reverse)     

-(NSString *)reverseString {     

}   @end  

The two files created are named: NSString+reverse.h (interface) And NSString+reverse.m (implementation).

Page 46: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

E XTE NS IONS

v  Classextensionsarelike“anonymous”categories,exceptthat

themethodstheydeclaremustbeimplementedinthemain

@implementation blockforthecorrespondingclass.@interface MyObject () - (void)setNumber:(NSNumber *)newNumber; @end

Page 47: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

CREATINGAS INGLETONstatic MySingleton* sharedSingleton = nil; + (MySingleton *) sharedSingleton {

if (sharedSingleton == nil) { sharedSingleton = [[super allocWithZone:NULL] init];

} return sharedSingleton ; } + (id)allocWithZone:(NSZone *)zone { return [[self

sharedSingleton ] retain]; } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (NSUInteger)retainCount {

return NSUIntegerMax; //denotes an object that cannot be released

} - (void)release { //do nothing } - (id)autorelease { return self; }

Page 48: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

FAST ENUMERATION

v Fastenumera;onisalanguagefeaturethatallowsyoutoefficientlyandsafelyenumerateoverthecontentsofacollec;onusingaconcisesyntax.

v Thesyntaxisdefinedasfollows:for(TypenewVariableinexpression){statements}

v orTypeexisKngItem;for(exisKngIteminexpression){statements}Ex:

for(NSString*elementinarray){ NSLog(@"element:%@",element);}

Page 49: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

SELECTORS v  Has two meanings:

•  Used to refer to the name of a method when it’s used in a source-code message to an object.

•  Also used to refer to the unique identifier that replaces the name when the source code is compiled.

•  Compiled selectors are of type SEL. •  All methods with the same name have the same selector. •  You can use a selector to invoke a method on an object •  this provides the basis for the implementation of the target-action design pattern in Cocoa.

Page 50: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

v  Instead of using full ASCII names , the compiler writes each method

name into a table, then pairs the name with a unique identifier that

represents the method at runtime.

v  The runtime system makes sure each identifier is unique: No two selectors

are the same, and all methods with the same name have the same selector.

v  Compiled selectors are assigned to a special type, SEL, to distinguish them

from other data

Page 51: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

SELsetWidthHeight;setWidthHeight=@selector(setWidth:height:);

•  TheperformSelector:,performSelector:withObject:,andperformSelector:withObject:withObject:methods,definedintheNSObjectprotocol,takeSELiden;fiersastheirini;alarguments

•  setWidthHeight=NSSelectorFromString(aBuffer);NSString*method;

•  method=NSStringFromSelector(setWidthHeight);

Page 52: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

EXCEPTIONHANDLING

v Objec;ve-C’sexcep;onsupportrevolvesaroundfour

compilerdirec;ves:@try,@catch,@throw,and@finally:

v Canre-throwthecaughtexcep;onusingthe@throw

direc;vewithoutanargumentinsidea@catch()block

v canthrowanyObjec;ve-Cobjectasanexcep;onobject.

v TheNSExcep;onclassprovidesmethodsthathelpin

excep;onprocessing,butitcanbecustomizedto

implementyourownifyousodesire.

Page 53: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

SYNCHRONIZINGTHREADEXECUTION

v  Objec;ve-Csupportsmul;threadinginapplica;ons.

v  Twothreadscantrytomodifythesameobjectatthesame;me,asitua;onthatcancauseseriousproblemsinaprogram.

v  Toprotectsec;onsofcodefrombeingexecutedbymorethanonethreadata;me,Objec;ve-Cprovidesthe@synchronized()direc;ve.

-(void)cri;calMethod{ @synchronized(self){ //Cri;calcode....

} }

v  The@synchronized()direc;vetakesasitsonlyargumentanyObjec;ve-Cobject,includingself

v  Thisobjectisknownasamutualexclusionsemaphoreormutex.

Page 54: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

v  TheObjec;ve-Csynchroniza;onfeaturesupportsrecursiveandreentrantcode

v Athreadcanuseasinglesemaphoreseveral;mesinarecursive

manner;otherthreadsareblockedfromusingitun;lthethread

releasesallthelocksobtainedwithit

v Whencodeinan@synchronized()blockthrowsanexcep;on,the

Objec;ve-Crun;mecatchestheexcep;on,releasesthesemaphore

(sothattheprotectedcodecanbeexecutedbyotherthreads),and

re-throwstheexcep;ontothenextexcep;onhandler.

Page 55: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

IMPORTANTFOUNDATIONCLASSES

v  Strings•  TheNSStringclass

v NumbersandDates•  UnlikestandardCfloats,integers,andsoforth,theseelements

areallobjects

v  CollecQons•  arrays,dic;onaries,andsets.

Page 56: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

v  NSString*myString=@"Astringconstant";

v  NSString*myString=[NSStringstringWithFormat:@"Thenumberis%d",5];

v  NSLog(@"%@",[myStringstringByAppendingString:@"22"]);

v  NSLog(@"%@",[myStringstringByAppendingFormat:@"%d",22]);

v  NSLog(@"%d",myString.length);//length

v  prinw("%c",[myStringcharacterAtIndex:2]);

v  ConverttoC-String:•  prinw("%s\n",[myStringUTF8String]);prinw("%s\n",

•  [myStringcStringUsingEncoding:NSUTF8StringEncoding]);

v  ConverttoNSString:•  [NSStringstringWithCString:"HelloWorld"encoding:NSUTF8StringEncoding]

Page 57: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

v Writeastringtoafile:•  [myStringwriteToFile:pathatomically:YESencoding:NSUTF8StringEncoding

error:&error]

v  Readingastringfromafile:•  NSString*inString=[NSStringstringWithContentsOfFile:path

encoding:NSUTF8StringEncodingerror:&error];

v  SplitaString:•  NSString*myString=@"OneTwoThreeFourFiveSixSeven";NSArray

*wordArray=[myStringcomponentsSeparatedByString:@""];

v  Substrings•  NSString*sub1=[myStringsubstringToIndex:7];•  NSString*sub2=[myStringsubstringFromIndex:4];

Page 58: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

v  SubstringusingarangeNSRanger;r.loca;on=4;r.length=2;NSString*sub3=[myStringsubstringWithRange:r];

v  searchastringforasubstringreturnsarangeNSRangesearchRange=[myStringrangeOfString:@"Five"];if(searchRange.loca;on!=NSNotFound)NSLog(@"Rangeloca;on:%d,length:%d",searchRange.loca;on,

searchRange.length);

v  replaceasubrangewithanewstring•  NSString*replaced=[myString

stringByReplacingOccurrencesOfString:@""withString:@"*"];

Page 59: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

v  Changestringcase•  [myStringuppercaseString];•  [myStringlowercaseString]);•  NSLog(@"%@",[myString capitalizedString]);

v  compareandteststrings•  [s1isEqualToString:s2],[s1hasPrefix:@"Hello"]•  [s1hasSuffix:@"Hello"]

v  Convertstringsintonumbersbyusingavaluemethod•  [s1intValue],[s1boolValue]);NSLog(@"%f",[s1floatValue]);NSLog(@"%f",[s1doubleValue]);

v Mutablestring•  NSMutableString*myString=[NSMutableStringstringWithString:@"HelloWorld."];•  [myStringappendFormat:@"Theresultsare%@now.",@"in"];

Page 60: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

NUMBERSANDDATES v NSNumberclass•  NSNumber*number=[NSNumbernumberWithFloat:3.141592];•  NSLog(@"%d",[numberintValue]);NSLog(@"%@",[numberstringValue]);

v Also:•  numberWithInt,numberWithFloat:,numberWithBool

Page 61: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

WORKINGWITHDATES v NSDateobjects-usenumberofsecondssinceanepoch(midnightonJanuary1,

2001.)(UnixepochismidnightonJanuary1,1970).

v  Current;me•  NSDate*date=[NSDatedate];/

v  Timerela;vetocurrent(10secfromnow)•  date=[NSDatedateWithTimeIntervalSinceNow:10.0f];

v  ShowDate•  NSLog(@"%@"[datedescrip;on]);•  UseNSDateFormaoerclass

v 

Page 62: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

TIMERS

v NSTimerclass•  [NSTimerscheduledTimerWithTimeInterval:1.0ftarget:self

selector:@selector(handleTimer:)userInfo:nilrepeats:YES];

v Disable;mer•  sendittheinvalidatemessage

•  [;merinvalidate];

Page 63: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

INDEXPATHS

v NSIndexPathClass

v  Storesthesec;onandrownumberforauserselec;onintables

v  indexPath.rowandindexPath.sec;onproper;es

Page 64: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

ARRAYS

v NSArray,NSMutableArrayclassesthatholdanytypeofobject•  NSArray*array=[NSArrayarrayWithObjects:@"One",@"Two",@"Three",nil];

v  array.count,[arrayobjectAtIndex:0],arrayWithArray:addObject:

removeObjectAtIndex:,arrayWithArray:arrayByAddingObjectsFromArray:

containsObject:,

v  Convertanarraytostring•  [arraycomponentsJoinedByString:@""]);

Page 65: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

DICTIONARIES v NSDic;onary,NSMutableDic;onary,classes

v  Createadic;onaryNSMutableDic;onary*dict=[NSMutableDic;onarydic;onary];[dictsetObject:@"1"forKey:@"A"];

v  Searchadic;onary[dictobjectForKey:@"A“];

v  Removeobjects[dictremoveObjectForKey:@"B"];

v  Listkeys•  [dictallKeys];

Page 66: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

SET OBJECTS

v NSSetclass

v Accesssetobjects:•  [aSetallObjects];

Page 67: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

v Arrays,setsanddic;onariesautoma;callyretainobjectswhenthey

areadded

v Andreleasethoseobjectswhentheyareremovedfromthe

collec;on.

v  Releasesarealsosentwhenthecollec;onisdeallocated.

v  Collec;onsdonotcopyobjects.

v  Theyrelyonretaincountstoholdontoobjectsandusethemas

needed.

Page 68: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

v  Writecollec;onstofiles(NSArray,NSDic;onary)•  writeToFile:atomically:•  Objectsmustbeoftype:NSData,NSDate,NSNumber,NSString,NSArray,and

NSDic;onary

v  Torecoveranarrayordic;onaryfromfile

•  NSArray*newArray=[NSArrayarrayWithContentsOfFile:path];•  AnddicKonaryWithContentsOfFile:

v NSURLobjectspointtoresources.•  TheseresourcescanrefertobothlocalfilesandtoURLsontheWeb.

•  NSURL*url1=[NSURLfileURLWithPath:path];forafile•  NSString*path=[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/foo.txt"];

•  NSURL*url2=[NSURLURLWithString:urlpath];fortheweb•  NSString*urlpath=@"hop://neu.edu";

Page 69: OBJECTIVE-C · 2019-02-03 · v A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code, but a message

v NSDataobjectscorrespondtobuffers.

v NSDataprovidesdataobjectsthatstoreandmanagebytes.

•  NSData*data=[NSDatadataWithContentsOfURL:url2];