Object—C

Objective-C is a general-purposeobject-orientedprogramming language thatadds Smalltalk-style messaging to the C programminglanguage. It is the main programming language used by Apple for the OSX and iOS operating systems andtheir respective APIsCocoa and Cocoa Touch.

Originally developed in the early 1980s, it wasselected as the main language used by NeXT forits NeXTSTEP operating system, from which OSX and iOS are derived.[1] Generic Objective-C programsthat do not use the Cocoa or Cocoa Touch libraries, or using partsthat may be ported or reimplemented for other systems can also be compiled forany system supported by GCC or Clang.

History[edit]

Objective-C was created primarily by Brad Cox and Tom Love in the early 1980sat their company Stepstone.[2] Both had been introduced to Smalltalk while at ITT Corporation's Programming TechnologyCenter in 1981. The earliest work on Objective-C traces back to around thattime.[3] Cox was intrigued by problemsof true reusability in software designandprogramming. He realized that a language like Smalltalk would be invaluable inbuilding development environments for system developers at ITT. However, he andTom Love also recognized that backward compatibility with C was criticallyimportant in ITT's telecom engineering milieu.[4]

Cox began writing a pre-processor for C to add someof the capabilities of Smalltalk. He soon had a working implementation of anobject-oriented extension to the C language, which he called "OOPC"for Object-Oriented Pre-Compiler.[5] Love was hired by SchlumbergerResearch in 1982 and had the opportunity to acquire the first commercial copyof Smalltalk-80, which further influenced the development of their brainchild.

In order to demonstrate that real progress could bemade, Cox showed that making interchangeable software componentsreallyneeded only a few practical changes to existing tools. Specifically, theyneeded to support objects in a flexible manner, come supplied with a usable setof libraries, and allow for the code (and any resources needed by the code) tobe bundled into a single cross-platform format.

Love and Cox eventually formed a new venture, Productivity Products International (PPI), tocommercialize their product, which coupled an Objective-C compiler with classlibraries. In 1986, Cox published the main description of Objective-C in itsoriginal form in the book Object-Oriented Programming, An EvolutionaryApproach. Although he was careful to point out that there is more to theproblem of reusability than just the language, Objective-C often found itselfcompared feature for feature with other languages.

Popularizationthrough NeXT[edit]

In 1988, NeXT licensedObjective-C from StepStone (the new name of PPI, the owner of the Objective-Ctrademark) and extended the GCC compilerto support Objective-C, and developed the AppKit and Foundation Kit libraries on which theNeXTstep user interface and interfacebuilder were based. While the NeXT workstations failed to make a great impactin the marketplace, the tools were widely lauded in the industry. This led NeXTto drop hardware production and focus on software tools, selling NeXTstep (andOpenStep) as a platform for custom programming.

The work to extend GCC wasled by Steve Naroff, who joined NeXT from StepStone. The compiler changes, butnot the runtime libraries, were made available as per GPL licenseterms rendering the open source contribution unusable to the general public.This led to other parties developing such under open source license. Later,Steve Naroff was also principal contributor to work at Apple to build theObjective-C frontend to Clang.

The GNU project started workon its free software implementation of Cocoa, named GNUstep, based on the OpenStepstandard.[6] Dennis Glatting wrote the firstGNU Objective-C runtime in1992. The GNU Objective-C runtime, which has been in use since 1993, is the onedeveloped by Kresten Krab Thorup when he was a university student inDenmark.[citation needed] Thorupalso worked at NeXT from 1993 to 1996.[citation needed]

After acquiring NeXT in 1996, Apple Computer used OpenStep in its newoperating system, Mac OS X. This includedObjective-C and NeXT's Objective-C based developer tool, Project Builder (which had been expandedand is now calledXcode), as well as its interface design tool, Interface Builder. Most of Apple's present-day Cocoa API is based on OpenStep interfaceobjects, and is the most significant Objective-C environment being used foractive development.

Syntax[edit]

Objective-C is a thin layer on top of C, and moreoveris a strict superset of C;it is possible to compile any C program with an Objective-C compiler, and tofreely include C code within an Objective-C class.[7]

Objective-C derives its object syntax from Smalltalk. All of the syntax fornon-object-oriented operations (including primitive variables, pre-processing,expressions, function declarations, and function calls) are identical to thatof C, while the syntax for object-oriented features is an implementation ofSmalltalk-style messaging.

Messages[edit]

The Objective-C model of object-oriented programmingis based on message passing toobject instances. In Objective-C one does not simply call a method;one sends a message. This is unlike the Simula-style programming model used byC++. The difference between these two concepts is in howthe code referenced by the method or message name is executed. In aSimula-style language, the method name is in most cases bound to a section of code in the targetclass by the compiler. In Smalltalk andObjective-C, the target of a message is resolved at runtime, with the receivingobject itself interpreting the message. A method is identified by a selector or SEL — a NUL-terminated stringrepresenting its name — and resolved to a C method pointer implementingit: an IMP.[8] A consequence of this is thatthe message-passing system has no type checking. The object to which themessage is directed — the receiver — is not guaranteed torespond to a message, and if it does not, it simply raises an exception.[9]

Sending the message method to the object pointed to by the pointer obj would require the following code in C++:

obj->method(argument);

In Objective-C, this is written as follows:

[obj method:argument];

Both styles of programming have their strengths andweaknesses. Object-oriented programming in the Simula (C++) style allows multiple inheritance andfaster execution by using compile-time binding wheneverpossible, but it does not support dynamic binding by default. It alsoforces all methods to have a corresponding implementation unless they areabstract.The Smalltalk-style programming as used in Objective-C allows messages to gounimplemented, with the method resolved to its implementation at runtime. Forexample, a message may be sent to a collection of objects, to which only somewill be expected to respond, without fear of producing runtime errors. Messagepassing also does not require that an object be defined at compile time. Animplementation is still required for the method to be called in the derivedobject. (See the dynamic typing section below for moreadvantages of dynamic (late) binding.)

Interfaces andimplementations[edit]

Objective-C requires that the interface andimplementation of a class be in separately declared code blocks. By convention,developers place the interface in a header file and the implementation in acode file. The header files, normally suffixed .h, are similar to C headerfiles while the implementation (method) files, normally suffixed .m, can bevery similar to C code files.

Interface[edit]

In other programming languages, this is called a"class definition".

The interface of a class is usually defined in aheader file. A common convention is to name the header file after the name ofthe class, e.g. Ball.h would containthe interface for the class Ball.

An interface declaration takes the form:

@interface classname : superclassname {

 // instance variables

}

+ classMethod1;

+ (return_type)classMethod2;

+ (return_type)classMethod3:(param1_type)param1_varName;

 

- (return_type)instanceMethod1With1Parameter:(param1_type)param1_varName;

- (return_type)instanceMethod2With2Parameters:(param1_type)param1_varName param2_callName:(param2_type)param2_varName;

@end

In the above, plus signs denote class methods, or methods that can be calledon the class itself (not on an instance), and minus signs denote instance methods, which can only be called ona particular instance of the class. Class methods also have no access toinstance variables.

The code above is roughly equivalent to the following C++ interface:

class classname : public superclassname {

 protected:

 // instance variables

 

 public:

 // Class (static)functions

 static void * classMethod1();

 static return_type classMethod2();

 static return_type classMethod3(param1_type param1_varName);

 

 // Instance (member)functions

 return_type instanceMethod1With1Parameter (param1_type param1_varName);

 return_type instanceMethod2With2Parameters (param1_type param1_varName, param2_typeparam2_varName=default);

};

Note that instanceMethod2With2Parameters:param2_callName: demonstratesthe interleaving of selector segments with argument expressions, for whichthere is no direct equivalent in C/C++.

Return types can be any standard C type, a pointer toa generic Objective-C object, a pointer to a specific type of object such asNSArray *, NSImage *, or NSString *, or a pointer to the class to which themethod belongs (instancetype). The default return type is the genericObjective-C type id.

Method arguments begin with a colon followed by theexpected argument type in parentheses and the argument name. In some cases(e.g. when writing system APIs) it is useful to add descriptive text beforeeach parameter.

- (void)setRangeStart:(int)start end:(int)end;

- (void)importDocumentWithName:(NSString *)name withSpecifiedPreferences:

(Preferences *)prefs beforePage:(int)insertPage;

Implementation[edit]

The interface only declares the class interface andnot the methods themselves: the actual code is written in the implementationfile. Implementation (method) files normally have the file extension .m, which originally signified"messages".[10]

@implementation classname

+ (return_type)classMethod

{

 // implementation

}

- (return_type)instanceMethod

{

 // implementation

}

@end

Methods are written using their interfacedeclarations. Comparing Objective-C and C:

- (int)method:(int)i

{

 return [self square_root:i];

}

int function (int i)

{

 return square_root(i);

}

The syntax allows pseudo-naming of arguments.

- (int)changeColorToRed:(float)red green:(float)green blue:(float)blue;

 

[myColor changeColorToRed:5.0 green:2.0 blue:6.0];

Internal representations of a method vary betweendifferent implementations of Objective-C. If myColor is of the class Color, instance method -changeColorToRed:green:blue: might beinternally labeled_i_Color_changeColorToRed_green_blue. The i is to refer to an instance method, with the class and then methodnames appended and colons changed to underscores. As the order of parameters ispart of the method name, it cannot be changed to suit coding style orexpression as with true named parameters.

However, internal names of the function are rarelyused directly. Generally, messages are converted to function calls defined inthe Objective-C runtime library. It is not necessarily known at link time whichmethod will be called because the class of the receiver (the object being sentthe message) need not be known until runtime.

Instantiation[edit]

Once an Objective-C class is written, it can beinstantiated. This is done by first allocating an uninitialized instance of theclass (an object) and then by initializing it. An object is not fullyfunctional until both steps have been completed. These steps should beaccomplished with a single line of code so that there is never an allocatedobject that hasn't undergone initialization (and because it is not advisable tokeep the intermediate result since -init can return adifferent object than that which it is called on).

Instantiation with the default, no-parameterinitializer:

MyObject *o = [[MyObject alloc] init];

Instantiation with a custom initializer:

MyObject *o = [[MyObject alloc] initWithString:myString];

In the case where no custom initialization is beingperformed, the "new" method can often be used in place of thealloc-init messages:

MyObject *o = [MyObject new];

Also, some classes implement class methodinitializers. Like +new, they combine +alloc and -init, but unlike +new, they return an autoreleasedinstance. Some class method initializers take parameters:

MyObject *o = [MyObject object];

MyObject *o2 = [MyObjectobjectWithString:myString];

The alloc message allocates enoughmemory to hold all the instance variables for an object, sets all the instancevariables to zero values, and turns the memory into an instance of the class;at no point during the initialization is the memory an instance of the superclass.

The init message performs the set-upof the instance upon creation. The init method is oftenwritten as follows:

- (id)init {

    self = [super init];

    if (self) {

        // perform initialization of object here

    }

    return self;

}

In the above example, notice the id return type. This type standsfor "pointer to any object" in Objective-C (See theDynamic typing section).

The initializer pattern is used in order to assurethat the object is properly initialized by its superclass before the initmethod performs its initialization. It performs the following actions:

1.    self = [super init]

Sends the superclass instance an init messageand assigns the result to self (pointer to the currentobject).

2.    if (self)

Checks if the returned object pointer is valid beforeperforming any initialization.

3.    return self

Returns the value of self to the caller.

A non-valid object pointer has the value nil;conditional statements like "if" treat nil like a null pointer, sothe initialization code will not be executed if [super init] returned nil. Ifthere is an error in initialization the init method should perform anynecessary cleanup, including sending a "release" message to self, andreturn nil to indicate that initialization failed. Anychecking for such errors must only be performed after having called thesuperclass initialization to ensure that destroying the object will be donecorrectly.

If a class has more than one initialization method,only one of them (the "designated initializer") needs to follow thispattern; others should call the designated initializer instead of thesuperclass initializer.

Protocols[edit]

In other programming languages, these are called"interfaces".

Objective-C was extended at NeXT tointroduce the concept of multiple inheritance ofspecification, but not implementation, through the introduction of protocols.This is a pattern achievable either as an abstract multiple inherited baseclass in C++, or as an "interface" (as inJava and C#). Objective-C makes use of ad hoc protocols called informalprotocols and compiler-enforced protocols called formalprotocols.

An informal protocol is a list of methods that aclass can opt to implement. It is specified in the documentation, since it hasno presence in the language. Informal protocols often include optional methods,which, if implemented, can change the behavior of a class. For example, a textfield class might have a delegate thatimplements an informal protocol with an optional method for performingauto-completion of user-typed text. The text field discovers whether thedelegate implements that method (via reflection)and, if so, calls the delegate's method to support the auto-complete feature.

A formal protocol is similar to an interface inJava or C#. It is a list of methods that any class can declare itself toimplement. Versions of Objective-C before 2.0 required that a class mustimplement all methods in a protocol it declares itself as adopting; thecompiler will emit an error if the class does not implement every method fromits declared protocols. Objective-C 2.0 added support for marking certainmethods in a protocol optional, and the compiler will not enforceimplementation of optional methods.

A class must be declared to implement that protocolto be said to conform to it. This is detectable at runtime. Formal protocolscannot provide any implementations; they simply assure callers that classesthat conform to the protocol will provide implementations. In the NeXT/Applelibrary, protocols are frequently used by the Distributed Objects system torepresent the capabilities of an object executing on a remote system.

The syntax

@protocol NSLocking

- (void)lock;

- (void)unlock;

@end

denotes that there is the abstract idea of locking.By stating that the protocol is implemented in the class definition:

@interface NSLock : NSObject <NSLocking>

//...

@end

Instances of NSLock claim that they will provide animplementation for the two instance methods.

Dynamic typing[edit]

Objective-C, like Smalltalk, can use dynamic typing: an object can be sent amessage that is not specified in its interface. This can allow for increasedflexibility, as it allows an object to "capture" a message and sendthe message to a different object that can respond to the messageappropriately, or likewise send the message on to another object. This behavioris known as message forwarding or delegation (seebelow). Alternatively, an error handler can be used in case the message cannotbe forwarded. If an object does not forward a message, respond to it, or handlean error, then the system will generate a runtime exception.[11] If messages are sent to nil (thenull object pointer), they will be silently ignored or raise a genericexception, depending on compiler options.

Static typing information may also optionally beadded to variables. This information is then checked at compile time. In thefollowing four statements, increasingly specific type information is provided.The statements are equivalent at runtime, but the additional information allowsthe compiler to warn the programmer if the passed argument does not match thetype specified.

- (void)setMyValue:(id)foo;

In the above statement, foo may beof any class.

- (void)setMyValue:(id<NSCopying>)foo;

In the above statement, foo may bean instance of any class that conforms to the NSCopying protocol.

- (void)setMyValue:(NSNumber *)foo;

In the above statement, foo must bean instance of the NSNumber class.

- (void)setMyValue:(NSNumber<NSCopying> *)foo;

In the above statement, foo must bean instance of the NSNumber class, and it must conform to the NSCopying protocol.

Forwarding[edit]

Objective-C permits the sending of a message to anobject that may not respond. Rather than responding or simply dropping themessage, an object can forward the message to an object that can respond.Forwarding can be used to simplify implementation of certain designpatterns, such as the observer pattern or the proxy pattern.

The Objective-C runtime specifies a pair of methodsin Object

·        forwarding methods:

- (retval_t)forward:(SEL)sel args:(arglist_t)args; // with GCC

- (id)forward:(SEL)sel args:(marg_list)args; // with NeXT/Apple systems

·        action methods:

- (retval_t)performv:(SEL)sel args:(arglist_t)args; // with GCC

- (id)performv:(SEL)sel args:(marg_list)args; // with NeXT/Apple systems

An object wishing to implement forwarding needs onlyto override the forwarding method with a new method to define the forwardingbehavior. The action method performv:: need not beoverridden, as this method merely performs an action based on the selector andarguments. Notice the SEL type, which isthe type of messages in Objective-C.

Note: in OpenStep, Cocoa, and GNUstep, the commonlyused frameworks of Objective-C, one does not use the Objectclass. The -(void)forwardInvocation:(NSInvocation *)anInvocation method of the NSObject class is used to do forwarding.

Example[edit]

Here is an example of a program that demonstrates thebasics of forwarding.

Forwarder.h

# import<objc/Object.h>

 

@interface Forwarder : Object {

 id recipient; //The object we want to forward themessage to.

}

 

//Accessor methods.

- (id)recipient;

- (id)setRecipient:(id)_recipient;

 

@end

Forwarder.m

# import"Forwarder.h"

 

@implementation Forwarder

 

- (retval_t)forward:(SEL)sel args:(arglist_t) args {

 /*

 * Check whether the recipient actuallyresponds to the message.

 * This may or may not be desirable, forexample, if a recipient

 * in turn does not respond to the message, itmight do forwarding

 * itself.

 */

 if([recipient respondsToSelector:sel]) {

  return [recipient performv:sel args:args];

 } else {

  return [self error:"Recipient does not respond"];

 }

}

 

- (id)setRecipient:(id)_recipient {

 [recipient autorelease];

 recipient = [_recipient retain];

 return self;

}

 

- (id) recipient {

 return recipient;

}

@end

Recipient.h

# import<objc/Object.h>

 

// A simple Recipientobject.

@interface Recipient : Object

- (id)hello;

@end

Recipient.m

# import"Recipient.h"

 

@implementation Recipient

 

- (id)hello {

 printf("Recipient says hello!\n");

 

 return self;

}

 

@end

main.m

# import"Forwarder.h"

# import"Recipient.h"

 

int main(void) {

 Forwarder *forwarder = [Forwarder new];

 Recipient *recipient = [Recipient new];

 

 [forwarder setRecipient:recipient]; //Set the recipient.

 /*

 * Observe forwarder does not respond to ahello message! It will

 * be forwarded. All unrecognized methods willbe forwarded to

 * the recipient

 * (if the recipient responds to them, aswritten in the Forwarder)

 */

 [forwarder hello];

 

 [recipient release];

 [forwarder release];

 

 return 0;

}

Notes[edit]

When compiled using gcc, thecompiler reports:

$ gcc -x objective-c-Wno-import Forwarder.m Recipient.m main.m -lobjc

main.m: In function`main':

main.m:12: warning:`Forwarder' does not respond to `hello'

$

The compiler is reporting the point made earlier,that Forwarder does not respond to hellomessages. In this circumstance, it is safe to ignore the warning sinceforwarding was implemented. Running the program produces this output:

$ ./a.out

Recipient says hello!

Categories[edit]

During the design of Objective-C, one of the mainconcerns was the maintainability of large code bases. Experience from the structuredprogramming world had shown that one of the main ways toimprove code was to break it down into smaller pieces. Objective-C borrowed andextended the concept of categories from Smalltalkimplementations to help with this process.[12]

Furthermore, the methods within a category are addedto a class at run-time.Thus, categories permit the programmer to add methods to an existing classwithout the need to recompile that class or even have access to its sourcecode. For example, if a system does not contain a spell checker in its Stringimplementation, it could be added without modifying the String source code.

Methods within categories become indistinguishablefrom the methods in a class when the program is run. A category has full accessto all of the instance variables within the class, including private variables.

If a category declares a method with the same method signature as an existing method ina class, the category’s method is adopted. Thus categories can not only addmethods to a class, but also replace existing methods. This feature can be usedto fix bugs in other classes by rewriting their methods, or to cause a globalchange to a class’s behavior within a program. If two categories have methodswith the same name (not to be confused with method signature), it is undefinedwhich category’s method is adopted.

Other languages have attempted to add this feature ina variety of ways. TOM tookthe Objective-C system a step further and allowed for the addition of variablesas well. Other languages have used prototypeoriented solutions instead, with the most notable being Self.

The C# and Visual Basic.NET languages implementsuperficially similar functionality in the form of extension methods, but these do not haveaccess to the private variables of the class.[13] Ruby andseveral other dynamic programming languages refer to the technique as "monkey patching".

Logtalk implements aconcept of categories (as first-class entities) that subsumes Objective-Ccategories functionality (Logtalk categories can also be used as fine-grainedunits of composition when defining e.g. new classes or prototypes; inparticular, a Logtalk category can be virtually imported by any number ofclasses and prototypes).

Example usage ofcategories[edit]

This example builds up an Integer class, by defining first a basic class with only accessor methods implemented,and adding two categories, Arithmetic and Display, which extend the basic class. While categories can access the base class’private data members, it is often good practice to access these private datamembers through the accessor methods, which helps keep categories moreindependent from the base class. This is one typical usage of categories—theother is to use categories to add or replace certain methods in the base class(however it is not regarded as good practice to use categories for subclassoverriding, also known as monkey patching). By convention filescontaining categories that extend base classes will take the name BaseClass+ExtensionClass.h.

Integer.h

# import<objc/Object.h>

 

@interface Integer : Object {

 int integer;

}

 

- (int) integer;

- (id) integer: (int) _integer;

@end

Integer.m

# import"Integer.h"

 

@implementation Integer

- (int) integer {

 return integer;

}

 

- (id) integer: (int) _integer {

 integer = _integer;

 

 return self;

}

@end

Integer+Arithmetic.h

# import"Integer.h"

 

@interface Integer (Arithmetic)

- (id) add: (Integer *) addend;

- (id) sub: (Integer *) subtrahend;

@end

Integer+Arithmetic.m

# import"Integer+Arithmetic.h"

 

@implementation Integer (Arithmetic)

- (id) add: (Integer *) addend {

 return [self integer: [self integer] + [addend integer]];

}

 

- (id) sub: (Integer *) subtrahend {

 return [self integer: [self integer] - [subtrahend integer]];

}

@end

Integer+Display.h

# import"Integer.h"

 

@interface Integer (Display)

- (id) showstars;

- (id) showint;

@end

Integer+Display.m

# import"Integer+Display.h"

 

@implementation Integer (Display)

- (id) showstars {

 int i, x = [self integer];

 for (i = 0; i < x; i++) {

 printf("*");

 }

 printf("\n");

 

 return self;

}

 

- (id) showint {

 printf("%d\n", [self integer]);

 

 return self;

}

@end

main.m

# import"Integer.h"

# import"Integer+Arithmetic.h"

# import"Integer+Display.h"

 

int main(void) {

 Integer *num1 = [Integer new], *num2 = [Integer new];

 int x;

 

 printf("Enter an integer: ");

 scanf("%d", &x);

 

 [num1 integer:x];

 [num1 showstars];

 

 printf("Enter an integer: ");

 scanf("%d", &x);

 

 [num2 integer:x];

 [num2 showstars];

 

 [num1 add:num2];

 [num1 showint];

 

 return 0;

}

Notes[edit]

Compilation is performed, for example, by:

gcc -x objective-cmain.m Integer.m Arithmetic.m Display.m -lobjc

One can experiment by omitting the #import "Arithmetic.h" and [num1 add:num2] lines and omit Arithmetic.m in compilation. The program will still run. This means that it ispossible to "mix-and-match" added categories if necessary; if onedoes not need to have some capability provided in a category, one can simplynot compile it in.

Posing[edit]

Objective-C permits a class to wholly replace anotherclass within a program. The replacing class is said to "pose as" thetarget class.

Note: Class posing was declared deprecated with Mac OS X v10.5, and is unavailable in the64-bit runtime.

For the versions still supporting posing, allmessages sent to the target class are instead received by the posing class.There are several restrictions:

·        A class may only pose as one of its direct orindirect superclasses.

·        The posing class must not define any new instancevariables that are absent from the target class (though it may define oroverride methods).

·        The target class may not have received any messagesprior to the posing.

Posing, similarly with categories, allows globalaugmentation of existing classes. Posing permits two features absent fromcategories:

·        A posing class can call overridden methods throughsuper, thus incorporating the implementation of the target class.

·        A posing class can override methods defined incategories.

For example,

@interface CustomNSApplication : NSApplication

@end

 

@implementation CustomNSApplication

- (void) setMainMenu: (NSMenu*) menu {

 // do something withmenu

}

@end

 

class_poseAs ([CustomNSApplication class], [NSApplication class]);

This intercepts every invocation of setMainMenu toNSApplication.

#import[edit]

In the C language, the #include pre-compile directive alwayscauses a file's contents to be inserted into the source at that point.Objective-C has the equivalent #import directiveexcept each file is included only once per compilation unit, obviating the needfor include guards.

Other features[edit]

Objective-C's features often allow for flexible, andoften easy, solutions to programming issues.

·        Delegating methods to other objects and remote invocation canbe easily implemented using categories and message forwarding.

·        Swizzling of the isa pointerallows for classes to change at runtime. Typically used for debugging where freed objects areswizzled into zombie objects whose only purpose is to report an error whensomeone calls them. Swizzling was also used in EnterpriseObjects Framework to create database faults. Swizzling is usedtoday by Apple’s Foundation Framework to implement Key-ValueObserving.

Language variants[edit]

Objective-C++[edit]

Objective-C++ is a language variant accepted by thefront-end to the GNU CompilerCollection and Clang, which can compilesource files that use a combination of C++ and Objective-C syntax.Objective-C++ adds to C++ the extensions that Objective-C adds to C. As nothingis done to unify the semantics behind the various language features, certainrestrictions apply:

·        A C++ class cannot derive from an Objective-C classand vice versa.

·        C++ namespaces cannot be declared inside anObjective-C declaration.

·        Objective-C declarations may appear only in globalscope, not inside a C++ namespace

·        Objective-C classes cannot have instance variables ofC++ classes that do not have a default constructor or that have one or morevirtual methods[citation needed],but pointers to C++ objects can be used as instance variables withoutrestriction (allocate them with new in the -init method).

·        C++ "by value" semantics cannot be appliedto Objective-C objects, which are only accessible through pointers.

·        An Objective-C declaration cannot be within a C++template declaration and vice versa. However, Objective-C types, (e.g.,Classname *) can be used as C++ template parameters.

·        Objective-C and C++ exception handling is distinct;the handlers of each cannot handle exceptions of the other type. This ismitigated in recent runtimes as Objective-C exceptions are either replaced byC++ exceptions completely (Apple runtime), or partly when Objective-C++ libraryis linked (GNUstep libobjc2).

·        Care must be taken since the destructor callingconventions of Objective-C and C++’s exception run-time models do not match(i.e., a C++ destructor will not be called when an Objective-C exception exitsthe C++ object’s scope). The new 64-bit runtime resolves this by introducinginteroperability with C++ exceptions in this sense.[14]

·        Objective-C blocks and C++11 lambdas are distinctentities, however a block is transparently generated on Mac OS X when passing alambda where a block is expected.[15]

Objective-C 2.0[edit]

At the 2006 WorldwideDevelopers Conference, Apple announced the release of"Objective-C 2.0," a revision of the Objective-C language to include"modern garbage collection, syntax enhancements,[16] runtime performanceimprovements,[17] and 64-bit support". Mac OS X v10.5, released in October 2007,included an Objective-C 2.0 compiler.GCC 4.6 supportsmany new Objective-C features, such as declared and synthesized properties, dotsyntax, fast enumeration, optional protocol methods, method/protocol/classattributes, class extensions and a new GNUnn Objective-C runtime API.[18]

Garbage collection[edit]

Objective-C 2.0 provided an optional conservative,generational garbagecollector. When run in backwards-compatiblemode,the runtime turned reference counting operationssuch as "retain" and "release" into no-ops.All objects were subject to garbage collection when garbage collection wasenabled. Regular C pointers could be qualified with "__strong" toalso trigger the underlying write-barrier compiler intercepts and thusparticipate in garbage collection.[19] A zero-ing weak subsystem wasalso provided such that pointers marked as "__weak" are set to zerowhen the object (or more simply, GC memory) is collected. The garbage collectordid not exist on the iOS implementation of Objective-C 2.0.[20] Garbage collection inObjective-C ran on a low-priority background thread, and can halt on userevents, with the intention of keeping the user experience responsive.[21]

Garbage collection was never made available in iOSdue to performance concerns. It was deprecated in OS X v10.8 in favour of AutomaticReference Counting (ARC) and is scheduled to be removed in afuture version of OS X.[22]

Properties[edit]

Objective-C 2.0 introduces a new syntax to declareinstance variables as properties,with optional attributes to configure the generation of accessor methods.Properties are, in a sense, public instance variables; that is, declaring aninstance variable as a property provides external classes with access (possiblylimited, e.g. read only) to that property. A property may be declared as"readonly", and may be provided with storage semantics such as"assign", "copy" or "retain". By default,properties are considered atomic, which results in a lock preventing multiplethreads from accessing them at the same time. A property can be declared as"nonatomic", which removes this lock.

@interface Person : NSObject {

 @public

 NSString *name;

 @private

 int age;

}

 

@property(copy) NSString *name;

@property(readonly) int age;

 

-(id)initWithAge:(int)age;

@end

Properties are implemented by way of the @synthesizekeyword, which generates getter (and setter, if not read-only) methodsaccording to the property declaration. Alternatively, the getter and settermethods must be implemented explicitly, or the @dynamic keyword can be used toindicate that accessor methods will be provided by other means. When compiledusing clang 3.1 or higher, all properties which is not explicitly declared with @dynamic, markedreadonly or have completeuser-implemented getter and setter will be automatically implicitly @synthesize'd.

@implementation Person

@synthesize name;

 

-(id)initWithAge:(int)initAge {

 self = [super init];

 if (self) {

 age = initAge; // NOTE: direct instance variable assignment, notproperty setter

 }

 return self;

}

 

-(int)age {

 return age;

}

@end

Properties can be accessed using the traditionalmessage passing syntax, dot notation, or, in Key-Value Coding, by name via the"valueForKey:"/"setValue:forKey:" methods.

Person *aPerson = [[Person alloc] initWithAge: 53];

aPerson.name = @"Steve"; // NOTE: dot notation, uses synthesized setter,

 // equivalent to[aPerson setName: @"Steve"];

NSLog(@"Access by message (%@), dot notation(%@),

property name(%@) anddirect instance variable access (%@)",

 [aPerson name], aPerson.name, [aPerson valueForKey:@"name"], aPerson->name);

In order to use dot notation to invoke propertyaccessors within an instance method, the "self" keyword should be used:

-(void)introduceMyselfWithProperties:(BOOL)useGetter {

 NSLog(@"Hi, my name is %@.", (useGetter ? self.name : name));

// NOTE: getter vs.ivar access

}

A class or protocol's properties may be dynamically introspected.

int i;

int propertyCount = 0;

objc_property_t *propertyList = class_copyPropertyList([aPerson class], &propertyCount);

 

for (i = 0; i < propertyCount; i++) {

 objc_property_t *thisProperty = propertyList + i;

 const char* propertyName = property_getName(*thisProperty);

 NSLog(@"Person has a property: '%s'", propertyName);

}

Non-fragile instancevariables[edit]

Objective-C 2.0 provides non-fragile instancevariables where supported by the runtime (i.e. when building 64-bit Mac OS Xcode as well as all iOS code). Under the modern runtime, an extra layer ofindirection is added to instance variable access, allowing the dynamic linkerto adjust instance layout at runtime. This feature allows for two importantimprovements to Objective-C code:

·        This eliminates the fragilebinary interface problem—superclasses can change sizes withoutaffecting binary compatibility.

·        This allows instance variables that provide thebacking for properties to be synthesized at runtime without them being declaredin the class’ interface.

Fast enumeration[edit]

Instead of using an NSEnumerator object or indices toiterate through a collection, Objective-C 2.0 offers the fast enumerationsyntax. In Objective-C 2.0, the following loops are functionally equivalent,but have different performance characteristics.

// Using NSEnumerator

NSEnumerator *enumerator = [thePeople objectEnumerator];

Person *p;

 

while ((p = [enumerator nextObject]) != nil) {

 NSLog(@"%@ is %i years old.", [p name], [p age]);

}

// Using indexes

for (int i = 0; i < [thePeople count]; i++) {

 Person *p = [thePeople objectAtIndex:i];

 NSLog(@"%@ is %i years old.", [p name], [p age]);

}

// Using fastenumeration

for (Person *p in thePeople) {

 NSLog(@"%@ is %i years old.", [p name], [p age]);

}

Fast enumeration generates more efficient code thanstandard enumeration because method calls to enumerate over objects arereplaced by pointer arithmetic using the NSFastEnumeration protocol.[23]

 

Class Extensions[edit]

A class extension has the same syntax as a categorydeclaration with no category name, and the methods and properties declared init are added directly to the main class. It is mostly used as an alternative toa category to add methods to a class without advertising them in the publicheaders, with the advantage that for class extensions the compiler checks thatall the privately declared methods are actually implemented. [24]

Implications forCocoa development[edit]

This section does not cite any references or sources. Please help improve this section by adding citations to reliable sources. Unsourced material may be challenged and removed(November 2012)

All Objective-C applications developed for Mac OS Xthat make use of the above improvements for Objective-C 2.0 are incompatiblewith all operating systems prior to 10.5 (Leopard). Since fast enumeration doesnot generate exactly the same binaries as standard enumeration, its use willcause an application to crash on OS X version 10.4 or earlier.

Blocks[edit]

Main article: Blocks (Clanguage extension)

Blocks is a nonstandard extension for Objective-C (aswell as C and C++) that uses special syntax to create closures.Blocks are only supported in Mac OS X 10.6"Snow Leopard" or later and iOS 4 or later, as well as GNUstep with libobjc2 1.7and compiling with clang 3.1 or later.[25]

#include<stdio.h>

#include <Block.h>

typedef int (^IntBlock)();

 

IntBlock MakeCounter(int start, int increment) {

        __block int i = start;

 

        return Block_copy( ^ {

               int ret = i;

               i += increment;

               return ret;

        });

 

}

 

int main(void) {

        IntBlock mycounter = MakeCounter(5, 2);

        printf("First call: %d\n", mycounter());

        printf("Second call: %d\n", mycounter());

        printf("Third call: %d\n", mycounter());

 

        /* because it was copied, it mustalso be released */

        Block_release(mycounter);

 

        return 0;

}

/* Output:

        First call: 5

        Second call: 7

        Third call: 9

*/

Modern Objective-C[edit]

Automatic ReferenceCounting[edit]

Main article: AutomaticReference Counting

Automatic Reference Counting (ARC) is a compile-timefeature that eliminates the need for programmers to manually manage retaincounts using retain and release.[26] Unlike garbagecollection, which occurs at run time, ARC eliminates the overhead ofa separate process managing retain counts. ARC and manual memory management arenot mutually exclusive; programmers can continue to use non-ARC code inARC-enabled projects by disabling ARC for individual code files. XCode can alsoattempt to automatically upgrade a project to ARC.

Literals[edit]

NeXT and Apple Obj-C runtimes have long included ashort-form way to create new strings, using the literal syntax @"a new string". Using this formatsaves the programmer from having to use the longer initWithString or similar methods when doingcertain operations.

When using Apple LLVM compiler4.0 or later, arrays, dictionaries, and numbers (NSArray, NSDictionary, NSNumberclasses) can also be created usingliteral syntax instead of methods.[27] Literal syntax uses the @ symbol combined with [], {}, (), to create theclasses mentioned above, respectively.[28]

Example without literals:

NSArray *myArray = [NSArray arrayWithObjects:object1,object2,object3,nil];

NSDictionary *myDictionary1 = [NSDictionary dictionaryWithObject:someObject forKey:@"key"];

NSDictionary *myDictionary2 = [NSDictionary dictionaryWithObjectsAndKeys:object1, key1, object2, key2, nil];

NSNumber *myNumber = [NSNumber numberWithInt:myInt];

NSNumber *mySumNumber = [NSNumber numberWithInt:(2 + 3)];

NSNumber *myBoolNumber = [NSNumber numberWithBool:YES];

Example with literals:

NSArray *myArray = @[ object1, object2, object3 ];

NSDictionary *myDictionary1 = @{ @"key" : someObject };

NSDictionary *myDictionary2 = @{ key1: object1, key2: object2 };

NSNumber *myNumber = @(myInt);

NSNumber *mySumNumber = @(2+3);

NSNumber *myBoolNumber = @YES;

However, different from string literals, whichcompile to actual constants in the executable, these literals compile to codeequivalent to the above method calls. In particular, under manuallyreference-counted memory management, these objects are autoreleased, whichrequires additional care when e.g. used with function-static variables or otherkinds of globals.

Subscripting[edit]

When using Apple LLVM compiler4.0 or later, arrays and dictionaries (NSArray and NSDictionary classes) can be manipulatedusing subscripting.[27] Subscripting can be used toretrieve values from indexes (array) or keys (dictionary), and with mutableobjects, can also be used to set objects to indexes or keys. In code,subscripting is represented using brackets [ ].[28]

Example without subscripting:

id object1 = [someArray objectAtIndex:0];

id object2 = [someDictionary objectForKey:@"key"];

[someMutableArray replaceObjectAtIndex:0 withObject:object3];

[someMutableDictionary setObject:object4 forKey:@"key"];

Example with subscripting:

id object1 = someArray[0];

id object2 = someDictionary[@"key"];

someMutableArray[0] = object3;

someMutableDictionary[@"key"] = object4;

"Modern"Objective-C syntax (1997)[edit]

After the purchase of NeXT by Apple, attempts weremade to make the language more familiar to existing programmers. One of theseattempts was the introduction of what was dubbed "Modern Syntax" forObjective-C at the time[29] (as opposed to the current,"classic" syntax). There was no change in actual behaviour, this wasmerely an alternative syntax. Instead of writing a method invocation like

   object = [[Class alloc] init];

   [object firstLabel: param1 secondLabel:param2];

It was instead written as

   object = (Class.alloc).init;

   object.firstLabel ( param1, param2 );

Similarly, declarations went from the form

   -(void) firstLabel: (int)param1 secondLabel:(int)param2;

to

  -(void) firstLabel ( int param1, int param2 );

This "modern" syntax is no longer supportedin current dialects of the Objective-C language.

Portable ObjectCompiler[edit]

Besides the GCC/NeXT/Apple implementation, which added severalextensions to the original Stepstone implementation,another free,open-source Objective-C implementation called the PortableObject Compiler[30] also exists. The set ofextensions implemented by the Portable Object Compiler differs from theGCC/NeXT/Apple implementation; in particular, it includes Smalltalk-like blocks for Objective-C, whileit lacks protocols and categories, two features used extensively in OpenStepand its derivatives and relatives. Overall, POC represents an older, pre-NeXTstage in the language's evolution, roughly conformant to Brad Cox's 1991 book.

It also includes a runtime library called ObjectPak,which is based on Cox's original ICPak101 library (which in turn derives fromthe Smalltalk-80 class library), and is quite radically different from theOpenStep FoundationKit.

GEOS Objective-C[edit]

The PC GEOS systemused a programming language known as GEOS Objective-C or goc;[31] despite the name similarity,the two languages are similar only in overall concept and the use of keywordsprefixed with an @ sign.

Clang[edit]

The Clang compiler suite,part of the LLVM project, implements Objective-C aswell as other languages.

Library use[edit]

Objective-C today is often used in tandem with afixed library of standard objects (often known as a "kit" or"framework"), such as CocoaGNUstep or ObjFW.These libraries often come with the operating system: the GNUstep librariesoften come with GNU/Linux baseddistributions and Cocoa comes with OS X. The programmer is not forced toinherit functionality from the existing base class (NSObject / OFObject).Objective-C allows for the declaration of new root classes that do not inheritany existing functionality. Originally, Objective-C based programmingenvironments typically offered an Object class as the base class from whichalmost all other classes inherited. With the introduction of OpenStep, NeXTcreated a new base class named NSObject, which offered additional features overObject (an emphasis on using object references and reference counting insteadof raw pointers, for example). Almost all classes in Cocoa inherit fromNSObject.

Not only did the renaming serve to differentiate thenew default behavior of classes within the OpenStep API, but it allowed codethat used Object—the original base class used on NeXTSTEP (and, more or less,other Objective-C class libraries)—to co-exist in the same runtime with codethat used NSObject (with some limitations). The introduction of the two letterprefix also became a simplistic form of namespaces, which Objective-C lacks.Using a prefix to create an informal packaging identifier became an informalcoding standard in the Objective-C community, and continues to this day.

More recently, package managers have startedappearing, such as CocoaPods, which aims tobe both a package manager and a repository of packages. A lot of open-sourceObjective-C code that was written in the last years can now be installed usingCocoaPods.

Analysis of thelanguage[edit]

This section needs additional citations for verification. Please helpimprove this article by adding citations to reliable sources. Unsourced material may be challenged and removed. (December 2011)

Objective-C implementations use a thin runtime system written in C, which addslittle to the size of the application. In contrast, most object-orientedsystems at the time that it was created used large virtual machine runtimes. Programswritten in Objective-C tend to be not much larger than the size of their codeand that of the libraries (which generally do not need to be included in thesoftware distribution), in contrast to Smalltalk systems where a large amountof memory was used just to open a window. Objective-C applications tend to belarger than similar C or C++ applications because Objective-C dynamic typingdoes not allow methods to be stripped or inlined. Since the programmer has suchfreedom to delegate, forward calls, build selectors on the fly and pass them tothe runtime system, the Objective-C compiler cannot assume it's safe to removeunused methods or to inline calls.

Likewise, the language can be implemented on top ofexisting C compilers (in GCC,first as a preprocessor, then as a module) rather than as a new compiler. Thisallows Objective-C to leverage the huge existing collection of C code,libraries, tools, etc. Existing C libraries can be wrapped in Objective-C wrappers to provide an OO-styleinterface. In this aspect, it is similar to GObject library and Vala language,which are widely used in development of GTKapplications.

All of these practical changes lowered the barrier to entry, likely the biggest problemfor the widespread acceptance of Smalltalk in the 1980s.

The first versions of Objective-C did not support garbagecollection. At the time this decision was a matter of some debate,and many people considered long "dead times" (when Smalltalk didcollection) to render the entire system unusable. Some 3rd partyimplementations have added this feature (most notably GNUstep) and Apple hasimplemented it as of Mac OS X v10.5.[32] However in more recentversions of Mac OS X and iOS, garbage collection has been deprecated in favorof ARC (see below).

Another common criticism is that Objective-C does nothave language support for namespaces. Instead,programmers are forced to add prefixes to their class names, which aretraditionally shorter than namespace names and thus more prone to collisions.As of 2007, all Mac OS X classes and functions in the Cocoa programming environment areprefixed with "NS" (e.g. NSObject, NSButton) to identify them asbelonging to the Mac OS X or iOS core; the "NS" derives from thenames of the classes as defined during the development of NeXTstep.

Since Objective-C is a strict superset of C, it doesnot treat C primitive types as first-class objects.

Unlike C++, Objective-C does not support operator overloading.Also unlike C++, Objective-C allows an object to directly inherit only from oneclass (forbidding multiple inheritance).However, categories and protocols may be used as an alternative way to achievethe same results.

Because Objective-C uses dynamic runtime typing andbecause all method calls are function calls (or, in some cases, syscalls), manycommon performance optimizations cannot be applied to Objective-C methods (forexample: inlining, constant propagation, interprocedural optimizations, andscalar replacement of aggregates). This limits the performance of Objective-Cabstractions relative to similar abstractions in languages such as C++ wheresuch optimizations are possible.

Many programmers[who?] dislikegarbage collected languages because of the runtime performance tradeoffs. Appleintroduced AutomaticReference Counting (ARC) in 2011 as an alternative memorymanagement mechanism. With ARC, the compiler inserts retain and release callsautomatically into Objective-C code based on static code analysis. Theautomation relieves the programmer of having to write in memory managementcode. ARC also adds weak references to the Objective-C language.

Philosophicaldifferences between Objective-C and C++[edit]

The design and implementation of C++ and Objective-C represent different approaches toextending C.

In addition to C’s style of procedural programming,C++ directly supports certain forms of object-orientedprogramminggeneric programming,and metaprogramming.C++ also comes with a large standard library that includes several containerclasses. Similarly, Objective-C adds object-orientedprogrammingdynamic typing, and reflection toC. Objective-C does not provide a standard library, per se, but in most placeswhere Objective-C is used, it is used with an OpenStep-like library such as OPENSTEPCocoa, or GNUstep, which provide functionality similarto C++’s standard library.

One notable difference is that Objective-C providesruntime support for reflective features,whereas C++ adds only a small amount of runtime support to C. In Objective-C,an object can be queried about its own properties, e.g., whether it willrespond to a certain message. In C++ this is not possible without the use ofexternal libraries.

The use of reflection is part of the widerdistinction between dynamic (run-time) features versus static (compile-time)features of a language. Although Objective-C and C++ each employ a mix of bothfeatures, Objective-C is decidedly geared toward run-time decisions while C++is geared toward compile-time decisions. The tension between dynamic and staticprogramming involves many of the classic trade-offs in programming: dynamicfeatures add flexibility, static features add speed and type checking.

Generic programming and metaprogramming can beimplemented in both languages using runtime polymorphism; in C++ this takes theform of virtual functions and runtime type identification, while Objective-Coffers dynamic typing and reflection. Objective-C lacks compile-timepolymorphism (generics) entirely, while C++ does support this via functionoverloading and templates.

 

See also[edit]

·        C (programming language)

·        C++

·        Comparison ofprogramming languages

·        Xcode

References[edit]

1.   Jump up^ Singh, Amit (December 2003). "A Brief History of Mac OS X". Mac OS X Internals.Retrieved 11 June 2012.

2.   Jump up^ Garling, Caleb. "iPhone Coding Language Now World’s Third Most Popular"Wired. Retrieved May 20, 2013.

3.   Jump up^ Wentk, Richard (2009). Cocoa: Volume 5 of Developer Reference Apple Developer Series.John Wiley and Sons,.ISBN 0-470-49589-8.

4.   Jump up^ Biancuzzi, Federico; Warden, Shane (2009). Masterminds of ProgrammingO'Reilly Media, Inc. pp. 242–246. ISBN 0-596-51517-0.

5.   Jump up^ Cox, Brad (1983). "The objectoriented pre-compiler: programming Smalltalk 80 methods in C language"ACMSIGPLAN Notices (New York, NY: ACM18 (1).doi:10.1145/948093.948095.Retrieved 2011-02-17.

6.   Jump up^ "GNUstep:Introduction". GNUstep developers/GNU Project. Retrieved2012-07-29.

7.   Jump up^ "Write Objective-C Code". apple.com. 2013-04-23.Retrieved 2013-12-22.

8.   Jump up^ Apple, Inc. (19 October 2009). "Dynamic Method Resolution"Objective-CRuntime Programming Guide. Retrieved {{subst:today}}.

9.   Jump up^ Apple, Inc. (19 October 2009). "Avoiding Messaging Errors"The Objective-CProgramming Language. Retrieved {{subst:today}}.

10. Jump up^ Dalrymple, Mark; Knaster,Scott. Learn Objective-C on the Mac. p. 9. "The .mextension originally stood for "messages" when Objective-C was firstintroduced, referring to a central feature of Objective-C"

11. Jump up^ "Objective-C Runtime Programming Guide". Apple Inc.

12. Jump up^ Example of categories concept

13. Jump up^ "ExtensionMethods (C# Programming Guide)". Microsoft. October 2010.Retrieved 2011-07-10.

14. Jump up^ Using C++ With Objective-C in Mac OS X Reference Library,last retrieved in 2010-02-10.

15. Jump up^ [1]

16. Jump up^ "Objective-C 2.0: more clues". Lists.apple.com.2006-08-10. Retrieved 2010-05-30.

17. Jump up^ "Re: Objective-C 2.0". Lists.apple.com. Retrieved2010-05-30.

18. Jump up^ "GCC 4.6Release Series: Changes, New Features, and Fixes".

19. Jump up^ Garbage Collection Programming Guide: Garbage Collection API (Appledeveloper website - search for "__strong")

20. Jump up^ "Garbage Collection Programming Guide: Introduction to GarbageCollection". Apple Inc. 2011-10-03.

21. Jump up^ "Leopard Technology Series for Developers: Objective-C 2.0Overview". Apple Inc. 2007-11-06. Archived from the original on July 24, 2010. Retrieved 2010-05-30.

22. Jump up^ "Transitioning to ARC Release Notes". Apple Inc.2012-07-17. Retrieved 2012-08-26.

23. Jump up^ Apple, Inc. (2009). "Fast Enumeration". apple.com. Retrieved 2009-12-31.

24. Jump up^ Free Software Foundation, Inc.(2011). "GCC 4.6Release Series – Changes, New Features, and Fixes".http://gcc.gnu.org.Retrieved 2013-11-27.

25. Jump up^ "Blocks Programming Topics – Mac Developer Library".Apple Inc. March 8, 2011. Retrieved November 28, 2012.

26. Jump up^ "Transitioning to ARC". Apple Inc. Retrieved 8October 2012.

27. Jump up to:a b "Programming with Objective-C: Values and Collections".Apple Inc. Retrieved 8 October 2012.

28. Jump up to:a b http://clang.llvm.org/docs/ObjectiveCLiterals.html

29. Jump up^ Rhapsody Developer's Guide,AP Professional, 1997

30. Jump up^ "PortableObject Compiler". Users.pandora.be. 1970-01-01. Retrieved2010-05-30.

31. Jump up^ "Breadbox Computer Company LLC homepage". Retrieved8 December 2010.

32. Jump up^ Apple, Inc. (August 22,2006). "Mac OS X Leopard – Xcode 3.0". apple.com. Retrieved2006-08-22.[dead link]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章