Minggu, 03 Juni 2018

Sponsored Links

How to use #define in Objective C - Tutorial 90 - YouTube
src: i.ytimg.com

Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. It is the main programming language used by Apple for OS X and iOS operating systems, and their respective application programming interfaces -masing (API) Cocoa and Cocoa Touch before the introduction of Swift.

Objective-C programming language was originally developed in the early 1980s. It was chosen as the primary language used by NeXT for the NeXTSTEP operating system, from which OS X and iOS originated. A portable Objective-C program that does not use Cocoa or Cocoa Touch libraries, or that uses portables that can be ported or re-implemented for other systems, can also be compiled for any system supported by the GNU Compiler Collection (GCC) or Clang.

Program files 'implementations' Objective source code usually has the file name extension .m , while Objective-C 'header/interface' file has .h extension, same as C header file. Objective-C files are denoted by the .mm file extension.


Video Objective-C



History

Objective-C was created primarily by Brad Cox and Tom Love in the early 1980s in their company Stepstone. Both were introduced to Smalltalk at ITt Corporation's Programming Technology Center in 1981. The earliest work on Objective-C traces back to around that time. Cox is interested in the true reuse issues in software design and programming. He realized that languages ​​like Smalltalk would be invaluable in building a development environment for system developers in ITT. However, he and Tom Love also recognize that backward compatibility with C is critical in the ITT telecommunication engineering environment.

Cox started writing pre-processors for C to add some of the capabilities of Smalltalk. He soon had an implementation that worked from object-oriented extensions to C language, which he called "OOPC" for Object-Oriented Pre-Compiler. Love was hired by Schlumberger Research in 1982 and had the opportunity to acquire the first commercial copy of Smalltalk-80, which further influenced the development of their ideas.

To show that real progress can be made, Cox points out that making interchangeable software components really only requires some practical changes to existing tools. In particular, they need to support objects in a flexible way, complemented by a collection of user-friendly libraries, and allow code (and any resources required by the code) to be merged into one cross platform format.

Love and Cox eventually formed a new venture, International Product Productivity (PPI), to commercialize their products, combined with Objective-C compilers with class libraries. In 1986, Cox published a major description of Objective-C in its original form in Object Oriented Programming, Evolutionary Approach . Although he is careful to point out that there are more reusability problems than just language, Objective-C often finds itself compared to features for features with other languages.

Popularizing through NeXT

In 1988, NeXT granted an Objective-C license from StepStone (the new name of PPI, the owner of the Objective-C trademark) and expanded the GCC compiler to support Objective-C. NeXT developed the AppKit and Foundation Kit libraries where the NeXTSTEP user interface and Interface Builder are based. While NeXT workstations failed to make a big impact on the market, the tools were widely praised in the industry. This causes NeXT to lower hardware production and focus on software, selling NeXTSTEP (and OpenStep) as a platform for custom programming.

To avoid GPL provisions, initially NeXT intends to send a separate Objective-C frontend, allowing users to link it with GCC to generate an executable compiler. After initially accepted by Richard M. Stallman, this plan was rejected after Stallman consulted with GNU lawyers and NeXT agreed to create an Objective-C part of the GCC.

The work to expand GCC is led by Steve Naroff, who joined NeXT from StepStone. Compiler changes are made available under the terms of the GPL license, but the runtime library does not, rendering open source contributions can not be used for the general public. This causes the other party to develop the runtime library under an open source license. Later, Steve Naroff was also a major contributor to working at Apple to build an Objective-C frontend to the Clang.

The GNU project started working on the implementation of free software from Cocoa, named GNUstep, based on the OpenStep standard. Dennis Glatting wrote the first GNU Objective-C runtime in 1992. The GNU Objective-C runtime, which has been used since 1993, was developed by Kresten Krab Thorup when he was a student in Denmark. Thorup also worked at NeXT from 1993 to 1996.

Apple's Developer and Swift

After acquiring NeXT in 1996, Apple Computer uses OpenStep in its new operating system OS X. This includes Objective-C, Objective-C based developer tools, Project Builder, and interface design tools, Interface Builder, both now incorporated into one application , Xcode. Most of Apple's Cocoa APIs are currently based on the OpenStep interface object and are the most significant Objective-C environment used for active development.

At WWDC 2014, Apple introduced a new language, Swift, characterized as "Objective-C without the C".

Maps Objective-C



Syntax

Objective-C is a thin layer above C, and is a strict "superset" of C, meaning that it is possible to compile C program with Objective-C compiler, and to freely include C language code in Objective-C class.

Objective-C takes its object syntax from Smalltalk. All the syntax for non-object-oriented operations (including primitive variables, pre-processing, expressions, function declarations, and function calls) is identical to C, whereas the syntax for object-oriented features is a Smalltalk implementation - style message.

Message

The Objective-C object-oriented programming model is based on a message passing to an instance object. In Objective-C, someone does not call the method ; one send message . This is not like the Simula-style programming model used by C. The difference between these two concepts is how the code referenced by the method or name of the message is executed. In the Simula-style language, the method name is in most cases tied to the code part in the target class by the compiler. In Smalltalk and Objective-C, the target message is completed at runtime, with the recipient object itself interpreting the message. A method identified by the selector or SEL - string NUL -remove represents its name - and resolved to the method code pointer C: a IMP . The consequence of this is that the message-passing system does not have the type of checking. Objects geared towards messages - recipients - are not guaranteed to respond to messages, and if they do not, it raises an exception.

Sending method messages to objects pointed to by pointer obj will require the following code in C:

In Objective-C, it is written as follows:

Both programming styles have their strengths and weaknesses. Object-oriented programming in Simula style (C) allows faster inheritance and execution by using compile-time binding whenever possible, but does not support dynamic bindings by default. It also forces all methods to have the appropriate implementations unless they are abstract. Smalltalk-style programming as used in Objective-C allows messages to not be implemented, with methods that are completed for implementation at runtime. For example, a message can be sent to a collection of objects, which only a few are expected to respond to, without fear of generating a runtime error. Passing messages also does not require that objects be defined at compile time. Implementation is still needed for the method to be invoked in the derived object. (See the dynamic typing section below for more benefits of dynamic binding (too late).)

Interface and implementation

Objective-C requires that the interface and the class implementation be in a declared code block separately. By convention, the developer puts the interface in the header file and the implementation in the code file. The header file, usually suffixed.h, is similar to the C header file while the implementation file (method), usually suffixed.m, can be very similar to the C code file.

Interface

In other programming languages, this is called "class declaration".

The class interface is usually defined in the header file. The common convention is to name the header file after the class name, e.g. Ball.h will contain an interface for the Ball class.

The interface declaration takes the form:

Above, the plus signs indicate a class method, or a method that can be called in the class itself (not an instance), and a minus sign indicates an instant method, which can only be called on a particular instance of a class. The class method also does not have access to the instance variables.

The above code is more or less equivalent to the following C interface:

Note that instanceMethod2With2Parameters: param2_callName: shows the interleaving of the selector segment with an argument expression, which does not have a direct equivalent in C/C.

The return type may be of any standard C type, pointer to a generic Objective-C object, a pointer to a specific object type such as NSArray *, NSImage *, or NSString *, or a pointer to the class where the method belongs. (instancetype). The default return type is a generic Objective-C type id .

The argument method starts with a name that labeled the argument that is part of the method name, followed by a colon followed by the expected argument type in parentheses and argument names. Label can be removed.

Implementation

The interface just declares the class interface and not the method itself: the actual code is written in the implementation file. The file implementation (method) usually has a file extension .m , which was originally marked "message".

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

The syntax allows pseudo argument naming.

The internal representation of a method varies between different implementations of Objective-C. If myColor is a Color class, the instance method -changeColorToRed: green: blue: may be internally labeled _i_Color_changeColorToRed_green_blue . The i is to refer to an instance method, with the class and then the method name added and the colon is changed to the underscore. Since the parameter order is part of the method name, it can not be changed to match the coding or expression style as with the correct named parameter.

However, the internal name of the function is rarely used directly. Generally, messages are converted to a call function specified in the Objective-C runtime library. It is not always known at the time of the link that the method will be called because the recipient class (the object to which the message was sent) does not need to be known until processing time.

Instantiation

Once the Objective-C class is written, it can be used. This is done by first allocating instances of uninitialized classes (objects) and then by initializing. An object is not fully functional until both steps have been completed. These steps must be completed with a single line of code so that no object has ever been allocated that has not been initialized (and since it is unwise to keep intermediate results since -init can return an object different from it being called).

Instantiation with default, initializer without parameters:

Instantiation with special initializer:

In cases where no special initialisation is performed, the "new" method can often be used instead of the init-message allocation:

Also, some classes implement class method initialization. Like new , they combine alloc and -init , but unlike new , they return an autoreleased instance. Some initializers of class methods take parameters:

The alloc message allocates enough memory to hold all instances of an instance variable for an object, sets all instance variables to zero, and converts memory to a class instance; at no point during initialization is a superclass instance memory.

The init message performs an instance setting during creation. The init method is often written as follows:

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

The initializer pattern is used to ensure that the object is initialized correctly by the superclass before the init method initializes. It performs the following actions:

  1. self = [super init]
    Send a superclass instance of init and pass the result to self (pointer to the current object).
  2. if (self)
    Checks whether the returned object pointer is valid before initiating any initialization.
  3. get back
    Returns the value to the caller.

Invalid object pointer has value nil ; a conditional statement such as "if" treats zeros like a zero pointer, so initialization code will not run if [super init] is returned zero. If there is an error in initialization, the init method should perform the necessary cleanup, including sending a "release" message to itself, and returning nil to indicate that the initialization failed. Any checks for such errors should only be made after calling the superclass initialization to ensure that the destruction of the object will be done correctly.

If the class has more than one initialization method, only one of them ("designated initializer") needs to follow this pattern; the other should call the designated initializer instead of the superclass enabled.

Protocol

In other programming languages, this is called "interface".

Objective-C extended in NeXT to introduce the concept of multiple inheritance of specification, but not implementation, through protocol recognition. This is a pattern that can be achieved either as an abstract base class that is inherited in C, or as an "interface" (as in Java and C #). Objective-C uses an ad hoc protocol called informal protocol and a compiled-compiler protocol called formal protocol .

Informal protocol is a list of methods that a class can choose to implement. This is specified in the documentation, as there is no presence in the language. Informal protocols are implemented as categories (see below) on NSObject and often include optional methods, which, when applied, can change class behavior. For example, a text field class might have a delegate that implements informal protocols with optional methods for performing automatic completion of user typed text. The text field finds out whether the delegate implements the method (via reflection) and, if so, invokes the delegate method to support the autocomplete feature.

The formal protocol is similar to the interface in Java, C #, and Ada 2005. This is a list of methods that any class can apply to apply. Objective-C versions before 2.0 require that classes should implement all methods in protocols expressed as adoption; the compiler will emit an error if the class does not implement every method of the protocol it represents. Objective-C 2.0 adds support for marking certain methods in optional protocols, and the compiler will not enforce an optional method implementation.

The class must be declared to implement the protocol that must be said accordingly. It's detected at runtime. Formal protocols can not provide any implementation; they only reassure the caller that the class that complies with the protocol will provide implementation. In the NeXT/Apple library, the protocol is often used by Distributed Objects systems to represent the ability of an object that is executed on a remote system.

The syntax

indicating that there is an abstract idea of ​​locking. By stating in the class definition that the protocol is implemented,

an example of NSLock claims that they will provide implementations for two instant methods.

Dynamic typing

Objective-C, like Smalltalk, can use dynamic typing: objects can send messages not specified in the interface. This can allow for increased flexibility, as it allows objects to "capture" messages and send messages to different objects that can respond to messages appropriately, or also send messages to other objects. This behavior is known as message forwarding or delegate (see below). Or, error handlers can be used if messages can not be forwarded. If an object does not forward a message, respond to it, or handle an error, then the system will result in an exception of processing time. If the message is sent to nil (null object pointer), the message will be silently ignored or increase general exceptions, depending on the compiler option.

Static typing information can also be optionally added to a variable. This information is then checked at compile time. In the following four statements, more specific types of information are provided. The statement is equivalent at runtime, but additional information allows the compiler to warn the programmer if the arguments passed do not match the specified type.

In the above statement, foo may be of any class.

In the above statement, foo may be a derivative of any class corresponding to the NSCopying protocol.

In the above statement, foo must be a derivative of the NSNumber class.

In the above statement, foo must be a derivative of the NSNumber class, and it must match the NSCopying protocol.

Forwarding

Objective-C allows sending messages to objects that may not respond. Instead of responding or simply dropping a message, the object can forward a message to an object that can respond. Forwarding can be used to simplify the application of certain design patterns, such as observer patterns or proxy patterns.

The Objective-C runtime specifies a pair of methods at Object

  • forwarding method:
  • method of action:

An object that wants to apply forwarding only needs to replace the forwarding method with a new method to define forwarding behavior. The action method performv :: does not need to be replaced, because this method only performs actions based on the selector and argument. Note the type SEL , which is the message type in Objective-C.

Note: in OpenStep, Cocoa, and GNUstep, the commonly used Objective-C framework, someone does not use Object class. The - (void) forwardInvocation: (NSInvocation *) anInvocation method of the NSObject class is used for forwarding.

Example

Here is an example of a program that shows the basics of forwarding.

Forwarder.h
Forwarder.m
Recipients.h
Receiver.m
main.m

Note

When compiled using gcc, report the compiler:

 $ gcc -x objective-c -Wno-import Forwarder.m Recipient.m main.m -lobjc  main.m: In `main 'function:  main.m: 12: warning: `Forwarder 'does not respond` hello'  $  

The compiler reports previously created points, that Forwarder does not respond to hello messages. In these circumstances, it is safe to ignore warnings because forwarding is done. Running this program generates this output:

 $./a.out  The recipient greeted!  

Category

During the Objective-C design, one of the main concerns is the maintenance of a large codebase. The experience of a structured programming world has shown that one of the major ways to improve code is to break it down into smaller sections. Objective-C borrows and extends the concept category from Smalltalk's implementation to help this process.

Next, methods in the category are added to the class at run-time. Thus, the category allows the programmer to add a method to an existing class - an open class - without the need to recompile the class or even have access to its source code. For example, if a system does not contain a spell checker in a String implementation, it can be added without modifying the String source code.

The methods in the category become indistinguishable from the method in the class when the program is run. Category A has full access to all instance variables in the class, including private variables.

If a category declares a method with the same method signature as the method in the class, the category method is adopted. Thus the category can not only add methods to the class, but also replace the existing methods. This feature can be used to fix bugs in other classes by rewriting their methods, or causing global changes to classroom behavior in a program. If two categories have a method with the same name but a different method signature, no category method is specified which is adopted.

Other languages ​​have tried to add this feature in various ways. TOM takes the Objective-C system a step further and allows the addition of variables as well. Other languages ​​have used prototype-based solutions instead, the most prominent being Self.

The C # and Visual Basic.NET languages ​​implement very similar functions in the form of extension methods, but these do not have access to private variables of the class. Ruby and several other dynamic programming languages ​​refer to this technique as "monkey patching".

Logtalk implements the concept of a category (as a first-class entity) that subsumes category-C Category functionality (Logtalk categories can also be used as a fine unit of composition when defining for example a new class or prototype; in particular, the Logtalk category can be virtually imported by a number of classes and prototypes).

Examples of category usage

This example builds the Integer class, by defining the first base class with only the applied accessor method, and adding two categories, Arithmetic and Display , which extend base class. While the category can access members of the personal data of the base class, it is often a good practice to access members of this private data through the accessor method, which helps keep the category more independent of the base class. Implementing such access is one of the typical uses of the category. Another is to use categories to add methods to the base class. However, it is not considered a good practice to use categories for overriding subclasses, also known as patching monkeys. Informal protocols are implemented as categories in the NSObject base class. By convention, files containing categories that extend the base class will take the name of BaseClass ExtensionClass.h .

Integer.h
Integer.m
Integer Arithmetic.h
Integer Arithmetic.m
Integer Display.h
Integer Display.m
main.m

Note

Compilation is done, for example, by:

 gcc -x objective-c main.m Integer.m Integer Arithmetic.m Integer Display.m -lobjc  

One can experiment with leaving the line #import "Integer Arithmetic.h" and [num1 add: num2] and omitting Integer Arithmetic.m in compilation. The program will still run. This means that it is possible to mix-and-match categories added as needed; if a category does not need to have the ability, it can not be compiled.

Posing

Objective-C allows a class to completely replace other classes in a program. The replaced class is said to be "pose as" the target class.

The posing class is declared obsolete with Mac OS X v10.5, and is not available in 64-bit runtime. A similar function can be achieved by using the swizzling method in the category, which swaps the implementation of one method with another that has the same signature.

For versions that still support posing, all messages sent to the target class are even accepted by the posing class. There are some limitations:

  • Classes may only act as either direct or indirect superclasses.
  • The posing class should not define any new variables that do not exist from the target class (although they can specify or override methods).
  • The target class may not receive any messages before posing.

Posing, similar to category, enables global augmentation of existing classes. Posing allows two missing features of the category:

  • The posing class can invoke super overwritten methods, thus combining the implementation of the target class.
  • The posing class may override the method specified in the category.

As an example,

It cuts every request from setMainMenu to NSApplication.

# import

In C language, the pre-compile directive #include always causes the contents of the file to be inserted into the source at that point. Objective-C has a #import directive, which is equivalent except that each file is only included once per compilation unit, obviating the need to include guards.

Compiling Gcc Linux


Objective-C on the Mac L37 - Class Extensions - YouTube
src: i.ytimg.com


Other features

The Objective-C feature often allows flexible, and often easy, solutions to programming problems.

  • Delegating methods to other objects and remote requests can be easily implemented using category and message forwarding.
  • The swizzling of the isa pointer allows the class to change at runtime. Usually used for debugging where the freed object is crammed into a zombie object whose destination only reports errors when someone calls it. Swizzling is also used in Enterprise Objects Framework to make database errors. Swizzling is used today by the Apple Foundation Framework to implement Key-Value Observing.

Learn Objective-C Mac/iOS Tut: 1 (For Beginner Programmers) - YouTube
src: i.ytimg.com


Language variant

Objective-C

Objective-C is a language variant received by the front-end to the GNU Compiler Collection and Clang, which can compile source files using a combination of C and Objective-C syntax. Objective-C adds to C extension that Objective-C adds to C. Since nothing is done to unify the semantics behind various language features, certain restrictions apply:

  • Class C can not be derived from the Objective-C class and vice versa.
  • C namespaces can not be declared in the Objective-C declaration.
  • The Objective-C declaration may only appear in the global scope, not in the namespace C
  • The Objective-C class can not have an instance variable of class C that has no default constructor or that has one or more virtual methods, but a pointer to object C can be used as an instance variable without restriction (allocating it to the newly-in-method).
  • C "with semantic value" can not be applied to Objective-C objects, which can only be accessed via pointers.
  • Objective-C declaration must not be in template C declaration and vice versa. However, Objective-C types (eg, Classname *) can be used as template C parameters.
  • Control of exception Objective-C and C is different; each handler can not handle exceptions of other types. This was mitigated in recent runtimes because the Objective-C exception was replaced with the exception of C entirely (Apple runtime), or partly when the Objective-C library was connected (GNUstep libobjc2).
  • Care must be performed because the destructor invocation convention of the run-time exception model Objective-C and C does not match (ie, destructor C will not be invoked when the Objective-C exception exits the scope of object C). The new 64-bit runtime accomplishes this by introducing interoperability with the exception of C in this sense.
  • Objective-C blocks and C 11 lambdas are different entities. However, a block is created transparently on Mac OS X when it passes through lambda where a block is expected.

Objective-C 2.0

At the 2006 Worldwide Developer Conference, Apple announced the launch of "Objective-C 2.0," an Objective-C language revision to include "modern garbage collection, improved syntax, improved performance time and 64-bit support". Mac OS X v10.5, released in October 2007, includes the Objective-C 2.0 compiler. GCC 4.6 supports many new Objective-C features, such as declared and synthesized properties, point syntax, rapid enumeration, optional protocol methods, classroom protocol/class attributes, class extensions, and new GNU Objective-C API runtime.

Garbage collection

Objective-C 2.0 provides a conservative and generative optional garbage collector. When executed in a backward compatible mode, the runtime alters the reference counting operations such as "defend" and "release" to no-ops. All objects are subject to garbage collection when garbage collection is enabled. Regular C hints can be qualified with "__strong" to also trigger wiretapping of the basic engineering compiler and thus participate in garbage collection. A weak zero subsystem is also provided so that the pointer marked as "__weak" is set to zero when the object (or more accurately, GC memory) is collected. The garbage collector does not exist in the iOS Objective-C 2.0 implementation. Garbage collection in Objective-C runs on a low priority background thread, and can stop at user events, with the goal of maintaining a responsive user experience.

Garbage collection is no longer used in OS X v10.8 which supports Automated Reference Counting (ARC). Objective-C on iOS 7 runs on ARM64 using 19 bits of 64-bit word to store reference number, as marked pointer form.

Properties

Objective-C 2.0 introduces a new syntax for declaring an instance variable as a property, with an optional attribute to configure the generation of access methods. Property, in a sense, public instant variables; ie, declare an instance variable as a property provides an external class with access (possibly limited, eg read only) to that property. The property can be declared as "read only", and can be provided with a storage semantic such as assign , copy or retain . By default, the property is considered atomic , which generates a key that prevents some threads from accessing it at the same time. The property can be declared as nonatomic , which deletes this key.

The property is implemented by the @synthesize keyword, which results in a getter method (and setter, if not read-only) in accordance with the property statement. Alternatively, the getter and setter methods must be explicitly applied, or the @dynamic keyword can be used to indicate that the accessor method will be provided in other ways. When compiled using clang 3.1 or higher, all properties that are not explicitly declared with @dynamic , are marked readonly or have getters and setters implicitly implemented by the user will be implicitly @synthesize 'd.

The property can be accessed using a traditional message that forwards syntax, dot notation, or, in a Key-Value Coding, by name via the "valueForKey:"/"setValue: forKey:" method.

To use the dot notation to enable property accessors in an instance method, the keyword "self" should be used:

A class or protocol property may be dynamically introspected.

Non-fragile instant variables

Objective-C 2.0 provides non-fragile instant variables where supported by runtime (ie when building code for 64-bit Mac OS X, and all iOS). Under the modern runtime, an additional layer of hoax is added to the instance access variable, allowing dynamic links to adjust the instance layout at runtime. This feature allows for two important fixes for Objective-C code:

  • Eliminates the problem of fragile binary interface; superclasses can resize without affecting binary compatibility.
  • This allows instance variables that provide support for properties to be synthesized at run time without them being declared in the class interface.

Fast enumeration

Instead of using NSEnumerator or index objects for iterations through collections, Objective-C 2.0 offers a fast enumeration syntax. In Objective-C 2.0, the following loop is functionally equivalent, but has different performance features.

A quick enumeration produces code that is more efficient than a standard enumeration because the method call to calculate over objects is replaced by an arithmetic pointer using the NSFastEnumeration protocol.

Class extensions

Class extensions have the same syntax as category declarations without category names, and the methods and properties declared in them are added directly to the main class. It is mostly used as an alternative to categories to add methods to a class without their ads in the public header, with the advantage that for a class extension the compiler checks that all of the methods expressed in person are actually executed.

Implications for Cocoa development

All Objective-C applications developed for Mac OS X that use the above fixes for Objective-C 2.0 are not compatible with all operating systems prior to 10.5 (Leopard). Because the fast enumeration does not generate exactly the same binaries as the default enumeration, its use will cause application crashes in OS X version 10.4 or later.

Block

Blocks are nonstandard extensions for Objective-C (and C and C) that use special syntax to create closures. Blocks are only supported on Mac OS X 10.6 "Snow Leopard" or later, iOS 4 or later, and GNUstep with libobjc2 1.7 and compilation with clang 3.1 or later.

Modern Objective-C

Automatic Reference Count

Automatic Reference Counting (ARC) is a time-compilation feature that eliminates the need for programmers to manage retention counts using retaining and releasing manually. Unlike garbage collection, which occurs at run time, ARC eliminates the overhead of a separate process that manages the number of retirees. ARC and manual memory management are not mutually exclusive; programmers can continue to use non-ARC code in ARC-enabled projects by disabling ARC for individual code files. Xcode can also try to automatically upgrade the project to ARC.

Literal

NeXT and Apple Obj-C runtimes have long incorporated short-form ways to create new strings, using the @ "new string literal syntax, or down to the CoreFoundation kCFBooleanTrue and kCFBooleanFalse for NSNumber with a Boolean value. Using this format saves the programmer from having to reuse initWithString or similar methods when performing certain operations.

When using the LLVM 4.0 or newer Apple compiler, the array, dictionary, and number ( NSArray , NSDictionary , NSNumber classes) can also be created using literal syntax, not methods.

Examples without literals:

Examples with literals:

However, different from the literal string, which compiles constants in execution, this literal compiles code equivalent to the above method calls. Specifically, under reference memory management-calculated manually, these objects are autoreleased, which require additional maintenance when for example, are used with static-function variables or other types of global.

Subscripting

When using the LLVM 4.0 or newer Apple compiler, arrays and dictionaries ( NSArray and NSDictionary class) can be manipulated using subscripting. Subscripting can be used to retrieve values ​​from an index (array) or key (dictionary), and with a mutable object, can also be used to set an object to an index or key. In the code, subscripting is represented using the [] brackets.

Examples without subscripting:

Contoh dengan subscripting:

"Modern" Objective-C syntax (1997)

After the purchase of NeXT by Apple, efforts were made to make the language more acceptable to programmers who were more familiar with Java than Smalltalk. One of these efforts was to introduce what was dubbed "Modern Syntax" for Objective-C at the time (as opposed to the current "classical" syntax). No change in behavior, this is just an alternative syntax. Instead of writing a prayer like method

It was instead written as

Similarly, the declaration goes from the form

for

This "modern" syntax is no longer supported in the current Objective-C language dialect.

Portable Object Compiler

In addition to the GCC/NeXT/Apple implementation, which adds some extensions to the original Stepstone implementation, another free open source Objective-C implementation called Portable Object Compiler also exists. The set of extensions implemented by the Portable Object Compiler is different from the GCC/NeXT/Apple implementation; in particular, it includes Smalltalk-like blocks for Objective-C, while it lacks protocols and categories, two features that are widely used in OpenStep and its derivatives and relatives. Overall, the POC represents the older pre-NeXT stages in language evolution, roughly corresponding to 1991's book Brad Cox.

It also includes a runtime library called ObjectPak, based on the original ICPak101 Cox library (which in turn comes from the Smalltalk-80 class library), and quite radically different from the OpenStep FoundationKit.

GEOS Objective-C

The GEOS PC system uses a programming language known as GEOS Objective-C or goc ; Despite the similarity of names, these two languages ​​are only similar in overall concepts and the use of keywords beginning with the @ sign.

Clang

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

WinObjC

WinObjC (also known as "The Bridge") is an open source ObjC compiler project started by Microsoft in GitHub as a way to allow the reuse of iOS Application code inside Windows Universal Applications.

On Windows, the Objective-C Development tool is provided for download on the GNUStep website. The GNUStep Development System consists of the following packages: MSYS GNUstep System, GNUstep Core, GNUstep Devel, Cairo GNUstep, ProjectCenter IDE (Like Xcode, but not as complicated), Gorm (Interface Builder Like Xcode NIB builder).

1-Objective-C || What is objective C مقدمة عن اللغة - YouTube
src: i.ytimg.com


Library usage

Objective-C is now often used in conjunction with standard fixed object libraries (often known as "kits" or "skeletons"), such as Cocoa, GNUstep or ObjFW. These libraries often come with the operating system: GNUstep libraries often come with Linux-based distributions and Cocoa comes with OS X. Programmers are not forced to inherit functions from an existing base class (NSObject/OFObject). Objective-C allows for the declaration of a new root class that does not inherit an existing function. Initially, the Objective-C-based programming environment usually offers the Object class as the base class from which virtually all other classes are inherited. With the introduction of OpenStep, NeXT created a new base class called NSObject, which offers additional features on top of Objects (emphasis on object reference use and reference counting, not raw pointers, for example). Almost all classes in Cocoa inherit from NSObject.

Not only does renaming work to differentiate the default behavior of new classes in the OpenStep API, but it allows code that uses Object - the original base class used on NeXTSTEP (and, more or less, other Objective-C class libraries) - -to work together in runtime which is the same as code that uses NSObject (with some limitations). The introduction of the two-letter prefix is ​​also a simple form of the namespace, which has no Objective-C. Using the prefix to create an informal packaging identifier becomes an informal encoding standard within the Objective-C community, and continues to this day.

Recently, package managers have started emerging, such as CocoaPods, which aims to be a package manager and package repository. Many of the open-source Objective-C code written in recent years can now be installed using CocoaPods.

Objective C: working with Category in ios with an Example - YouTube
src: i.ytimg.com


Analysis of language

Objective-C implementation uses a thin runtime system written in C, which adds a bit to the size of the application. Instead, most object-oriented systems at the time were created using the runtimes of large virtual machines. Programs written in Objective-C tend to be not much larger than their code size and which of the libraries (which generally do not need to be included in the software distribution), in contrast to the Smalltalk system where a large amount of memory is used just to open windows. Objective-C applications tend to be larger than the same C or C applications because dynamic typing Objective-C does not allow methods to be stripped or underlined. Because the programmer has the freedom to delegate, forward calls, make the selector quickly and forward them to the runtime system, the Objective-C compiler can not assume safe to remove unused methods or for inline calls.

Likewise, the language can be implemented on top of an existing C compiler (in GCC, first as preprocessor, then as module) rather than as a new compiler. This allows Objective-C to utilize the collection of C code, libraries, tools, etc. The existing C library can be wrapped in Objective-C packets to provide an OO-style interface. In this aspect, it is similar to the GObject libraries and Vala languages, which are widely used in the development of GTK applications.

All these practical changes reduce the barriers to entry, possibly the biggest problem for Smalltalk's widespread acceptance in the 1980s.

The general criticism is that Objective-C has no language support for namespaces. Instead, programmers are forced to add prefixes to their class names, which are traditionally shorter than namespace names and thus more vulnerable to collisions. In 2007, all classes and functions of Mac OS X in the Cocoa programming environment started with "NS" (eg NSObject, NSButton) to identify them as part of the core of Mac OS X or iOS; "NS" derives from the class names as defined during the development of NeXTSTEP.

Since Objective-C is a strict superset C, it does not treat primitive types C as a first-class object.

Unlike C, Objective-C does not support operator overloading. Also unlike C, Objective-C allows an object to directly inherit from only one class (prohibiting multiple inheritance). However, in many cases, categories and protocols can be used as an alternative way to achieve the same results.

Because Objective-C uses dynamic runtime typing and since all method calls are function calls (or, in some cases, syscalls), many general performance optimizations can not be applied to the Objective-C method (eg: inlining, constant propagation, interprocedural optimization, and scalar replacement from aggregate). This limits the performance of Objective-C abstraction relative to a similar abstraction in a language like C where such optimization is possible.

Memory management

The first version of Objective-C does not support garbage collection. At the moment this decision is a matter of debate, and many people consider the "dead time" of the old (when Smalltalk did the collection) to make the whole system unusable. Some third-party implementations have added this feature (especially GNUstep) and Apple has implemented it on Mac OS X v10.5. However, in newer versions of Mac OS X and iOS, garbage collection has been discontinued for automatic reference counting (ARC), which was introduced in 2011.

With ARC, the insert compiler detains and releases calls automatically into Objective-C code based on static code analysis. Automation reduces the programmer must write in the memory management code. ARC also added a weak reference to Objective-C language.

Philosophical differences between Objective-C and C

The design and implementation of C and Objective-C is a fundamentally different approach to expanding C.

In addition to the procedural programming style C, C directly supports some form of object-oriented programming, generic programming, and metaprogramming. C also comes with a large standard library that includes several container classes. Similarly, Objective-C adds object-oriented programming, dynamic typing, and reflection to C. Objective-C does not provide standard libraries per se , but in most places where Objective-C is used, OpenStep-like libraries like OPENSTEP, Cocoa, or GNUstep, which provide functionality similar to standard C libraries.

One important difference is that Objective-C provides runtime support for reflective features, whereas C only adds a small amount of runtime support to C. In Objective-C, objects can be asked about its own properties, for example, whether to respond to a particular message. In C, this is not possible without using external libraries.

The use of reflection is part of a wider difference between a dynamic (run-time) feature and a static (time-compilation) feature of a language. Although Objective-C and C each use a combination of both features, Objective-C is clearly directed to a run-time decision while C is directed to a compile-time decision. The tension between dynamic and static programming involves many classic trade-offs in programming: dynamic features add flexibility, static features increase speed and type of checking.

Generic programming and metaprogramming can be implemented in both languages ​​using runtime polymorphism. In C it takes the form of virtual functions and identifies runtime types, while Objective-C offers dynamic typing and reflection. Objective-C does not have a full-time compile-polymorphism (generic function) completely, while C supports it through overloading functions and templates.

Learning Swift Programming Tutorial - Swift Vs Objective-C - YouTube
src: i.ytimg.com


See also

  • C (programming language)
  • C
  • Comparison of programming languages ​​
  • Comparison with COM, GObject, SOM, Windows Runtime, XPCOM
  • Swift
  • Xcode
  • WinObjC (aka: Microsoft Bridge for iOS)

cocoa - Objective-C: Making an NSArray from an NSString - Stack ...
src: i.stack.imgur.com


References


JSON tutorial in IOS 8 Objective C - YouTube
src: i.ytimg.com


Further reading


NSDictionary and NSMutableDictionary classes in Objective-C - YouTube
src: i.ytimg.com


External links

  • Programmed with Objective-C, from Apple (2012-12-13)
  • Objective-C Programming Language , from Apple (2011-10-11)
  • Objective-C Runtime Programming Guide , from Apple (2009-10-19)
  • Objective-C GNUstep Base Programming Manual
  • Objective-C by Brad Cox
  • Objective-C FAQ

Source of the article : Wikipedia

Comments
0 Comments