C + + Fast learning objective-c language Core grammar

Source: Internet
Author: User
Tags class definition constant garbage collection inheritance modifiers requires

This paper discusses the core grammar of language objective-c. This section begins by detailing some specific syntax. As you would expect, the definitions and classes are involved.

Classes are not special

In Smalltalk, a class is an object with some attributes. It's the same in Objective-c. A class is an object that responds to messages. Both Objective-c and C + + separate object allocation and initialization.

In C + +, object assignment passes a new action. In Objective-c, such an operation is done by sending an assignment message to the class-calling malloc () or an equivalence.

Initialization in C + + is by calling a function with the same name as the class. Objective-c does not distinguish between initialization methods and other methods, but the default initialization method for conventions is initialization.

When you declare a method to allow an instance to respond, the declaration usually has the "-" beginning, and "+" is used as a method of the class. It is common to use some prefixes for these messages in your document, so you can also say +alloc and-init to imply that Alloc is passed to a class, init to the instance.

Classes in Objective-c, just as in some other object-oriented languages, are object factories. Most classes do not implement +alloc on their own, but inherit from their parent classes. In NSObject, the parent class in most objective-c programs, +alloc method calls +allocwithzone:. Make Nszone as a parameter, a C structure contains some policies for object assignment. Looking back on the 1880s, Nszone is important for optimization when OBJECTIVE-C is used in NeXTSTEP to implement device-driven and GUI for CPU machines with only 8MB of memory 25MHZ. At the same time, this is more or less overlooked by objective-c programmers. (very likely to become as popular as NUMA architecture, more prevalent.) )

One of the many outstanding features is that object creation semantics are defined by the library and the language is not a cluster of ideas. When you pass a-INIT message to an object, it returns an initialization object. This may be the object you sent the message to, but it's not necessarily. This is consistent with other initialization programs. It is quite possible that special subclasses of some common classes are more effective on different data.

The common method for implementing this feature is called isa-swizzling. As I mentioned earlier, the Objective-c object is a C structure, and the first element of the structure is a pointer to a class. This element is accessible, just like other instance variables; You can change the object's class at run time by assigning new values. Of course, if you have a different layout for the object's class settings in memory, these settings can be seriously wrong.

However, you can define the layout by a parent class and set the behavior through a subset of sets, for example, this technique is used in a standardized string class (NSString), which has a variety of instances for different text character sets, static objects, and others.

Because classes are objects, you can manipulate them as you would an object. For example, you can put them in a collection. I use this format when I have some input events that need to be handled through instances of different classes. You need to create a directory mapping event named to the class, and then instantiate an object for each input event. If you do this in a library, it allows users of the code to easily register their own handles.

Types and pointers

Objective-c is not publicly allowed to define objects on the stack. But it's not true-it's possible to define an object on the stack, but it's a bit difficult because it destroys an assumption about memory management. As a result, each Objective-c object is a pointer. Some types are defined by OBJECTIVE-C, and these types are defined as type C in the head.

The 3 most common types of objective-c are Id,class and sel. The ID is the pointer to the Objective-c object, which is equivalent to the void* in the C language, and you can map any object pointer type to it and map to other object pointer types.

You can pass any message to the ID, but return a run-time exception if not supported.

Class is a pointer to the Objective-c class. Class is an object, you can also receive messages. The class name is a type, not mutable. The identifier NSObject is the type of a nsobject instance, but can also be used as a message recipient. You can get a class, as follows:

[NSObject class];

Send a +class message to the NSObject class, and then return a class structure pointer that represents the class.

This is very useful for our review [Fs:page], as we have seen in the second part of this series.

The third type of SEL represents a selector-an abstraction that represents the name of a method. You can create it directly by @selector () at compile time, or call Run-time library functions at run time through a C string, or use the OpenStep nsselectorfromstring () function to give the OBJECTIVE-C string a selector. This technique allows you to invoke methods by name. You can use a similar dlsym () in C, but it's very different in a C + +. In Objective-c, you can do the following:

[Object perfomselector: @selector (dosomething)];

This is equivalent to the following:

[Object dosomething];

Obviously, the second format is slightly faster because the first one transmits two messages. Later, we'll see some of the details handled through the selector.

C + + does not have the same type as the ID. Because objects can always be typed. In Objective-c, you can choose the type System. Both of these are valid:

ID object = @ "a string";

NSString *string = @ "a string";

The constant string is actually an instance of the Nsconstantstring class, and the Nsconstantstring class is a subclass of the nsstring. Referencing it to nsstring* causes the message to be type-checked at compile time and to store public instance variables (which have never been used in objective-c). Note that you can change this setting by changing the following:

Nsarray *array = (nsarray*) string;

If you send a message to an array, the compiler checks for messages that Nsarray can receive. This is not very useful, because the object is a string. It may be useful to send a nsarray and nsstring implementation message. If you send a message nsstring is not implemented, an exception will be thrown.

It seems strange to emphasize the difference between objective-c and C + +. Objective-c has type-value syntax, and C + + has type-variable syntax. In Objective-c, an object type is an object-specific attribute. In C + +, the type depends on the type of the variable.

In C + +, when you assign a pointer to an object to a variable to define a pointer to a parent class, two pointers may not have the same number (this can be implemented through multiple inheritance, which objective-c does not support). )

Defining classes

The Objective-c class definition has an interface and an implementation section. There are similar places with C + +, but two are slightly mixed.

Interfaces in objective-c only define bits and are explicitly required to be exposed. For the reason of implementation, this includes the private instance variable in most implementations, because you cannot inherit a class unless you know how big it is. Some of the most recent implementations, like Apple's 64-bit runtime, do not have this limitation.

The interface for the Objective-c object is as follows:

@interface Anobject:nsobject

{

@private

int Integerivar

@public

ID anotherobject;

}

+ (ID) aclassmethod;

-(ID) Aninstancemethod: (nsstring*) astring with: (ID) anobject

@end

The first line contains 3 parts. Identifier AnObject is the name of the new class. The name behind the colon is nsobject. (This is optional, but each Objective-c object should expand NSObject). The names in parentheses are protocols-similar to interfaces in Java-implemented by classes.

Just as a C + + instance variable (a domain in C + +) can access modifiers, unlike C + +, these modifiers are prefixed by @ To avoid conflicts with C identifiers.

OBJECTIVE-C does not support multiple inheritance, so there is only one parent class. Therefore, the layout of the first part of the object is always consistent with the layout of the parent class instance. This is often defined as dynamic in the past, meaning that changing an instance variable in a class requires all of its subclasses to be recompiled. This qualification does not require a slightly larger cost of accessing instance variables at the newer runtime. Another effect of this decision is to objective-c one of the other features.

Struct_anobject

{

@defs (AnObject);

};

@def represents the insertion of this structure into all fields of a particular object, so instances of the Struct_anobject and AnObject classes have the same memory structure. For example, you can use this rule to directly access instance variables. A common use is to allow the C function to manipulate objective-c objects directly, based on performance reasons.

As I hinted earlier, the other thing associated with this feature is that you can create objects on the stack. Because structs and objects have the same structure in the [fs:page] memory layout, you can simply create the structure, set his pointer to the correct class, and then map a pointer to an object pointer. Then you can use it as an object, although you have to be careful that nothing can keep the pointer out of bounds. (I never used this method in the real world, only theoretically.) )

Unlike C++,objective-c, there is no private or protected method. Any method on the Objective-c object can be invoked by another object. If you do not declare a method in an interface, you are informally private. You will get a run-time warning: the object does not respond to this message, but you can call it.

The interface is similar to the Head declaration in C. But it still needs an implementation, which is not surprising and can be defined using @implementation.

@implementation AnObject

+ (ID) aclassmethod

{

...

}

-(ID) Aninstancemethod: (nsstring*) astring with: (ID) anobject

{

...

}

@end

Note that the parameter type is specific, in parentheses. This is the reuse of the mapping syntax from C to show the value mapping to the type; they may not be types. The exact same rule is applied when mapping. This means that mapping between incompatible object pointer types can cause a warning (not an error).

Memory management

Traditionally, OBJECTIVE-C does not provide any memory management. In earlier versions, the object class implemented a +new method called malloc () to create a new object. When you finish using this object, send a-free message. Any object inherits from NSObject to respond to a-retain and-release message. When you finish using this object, you send a-free message. OpenStep added a reference calculation.

Each object inherited from NSObject responds to-retain and-release messages. When you want to keep a pointer to an object, you can send a-retain message. You can send a-release message when you are done with it.

There is a slight problem with this design. Usually you don't need to keep a pointer to the object, but you don't want to release it either. A typical example when returning an object, the caller needs to keep a pointer to the object, but you do not want to do so.

The solution to this problem is the NSAutoreleasePool class. Plus-retain and-release,nsobject also responded to-autorelease messages. When you send one, register with the current automatic release pool. When the pool object is logged off, it sends a-RELEASE message to each object, and the object receives the-autorelease message before that. In OpenStep applications, a NSAutoreleasePool instance is created at the beginning of the loop and destroyed at the end. You can also create your own instances to automatically release objects.

This mechanism reduces the replication required for some C + +. In fact, it is not worth doing, in objective-c, variability is the object's attributes, not reference. In C + +, there is a constant pointer and a very measure pointer. Calling the extraordinary method on a constant object is not allowed. It doesn't guarantee that the object will not be changed-just because you don't want to change.

In objective-c, a normal pattern defines a invariant class and a mutable subclass. NSString is a typical example;

It has a variable subclass of nsmutablestring. If you get nsstring and want to save it, you can send a-retain message and save the pointer without copying it. Instead, you can pass a +stringwithstring:message to NSString. The original pointer is checked and returned regardless of whether this parameter is variable.

When Apple and GNU run, OBJECTIVE-C supports storage garbage collection, which avoids the need for-retain and-release. The addition of language in the existing framework is not always well supported and requires extra care when used.

Summarize

Now that we have browsed the core of the Objective-c language, we will see some more advanced topics in this part of the summary.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.