In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/03 Report--
What is Objective-C?
Objective-C, referred to as OC, is a general, advanced, object-oriented programming language. It extends the standard ANSI C programming language
Add Smalltalk-style message passing mechanism to ANSI C. Currently, the main supported compilers are GCC and Clang (using LLVM as the back end).
The trademark of Objective-C belongs to Apple, which is the main developer of the programming language.
Apple used Objective-C to develop the NeXTSTEP operating system, which was later inherited by OS X and iOS.
Objective-C and Swift are now the main programming languages for OS X and iOS operating systems, and their associated API, Cocoa, and Cocoa Touch.
Objective-C is a strict superset of C language. This means that any C language program can go directly through the Objective-C compiler without modification.
It is also perfectly legal to use C code in Objective-C. Objective-C is described as a thin layer over the C language.
Because the original intention of Objective-C is to add object-oriented features to the C language body. The extensions commonly used in OC projects are as follows:
Extension content type
.h header file. The header file contains declarations of classes, types, functions, and constants.
M source code file. This is a typical source code file extension that can contain Objective-C and C code.
.mm source code file. Source code files with this extension can contain C++ code in addition to Objective-C and C code. Use this extension only if you really need to use C++ classes or features in your Objective-C code.
Hello, World!
Before learning any language, the basic thing you need to do is write and run a HelloWorld program, which is as follows for OC:
# import
Int main (int argc, const char * argv [])
{
@ autoreleasepool {NSLog (@ "Hello, World!");} return 0
}
Compile with clang:
Clang-framework Foundation hello.m-o hello
Run:
$. / hello
2019-04-05 09 World 33 World 22.579 hello [75742 World 3312942]
So easy! When we learn Objective-C, we should remember to focus on concepts rather than specific language details, so as to avoid falling into the situation of learning and useless.
Key concepts
Message passing
The biggest feature of Objective-C is the message passing model (message passing) inherited from Smalltalk.
This mechanism is very different from the mainstream style of C++ today. In Objective-C, instead of saying that objects call methods to each other
It is better to say that objects communicate messages to each other more accurately. The main difference between the two styles is the call method / messaging action.
In C++, the relationship between categories and methods is strictly clear, a method must belong to a category, and at compile time (compile time)
It is already tightly bound and it is not possible to call a method that does not exist in the category. But in Objective-C, the relationship between categories and messages is relatively loose.
Calling a method is treated as sending a message to the object, and all methods are treated as a response to the message. All messages are processed until run time (runtime)
The dynamic decision is made and it is left to the category to decide how to handle the received message. That is, a category does not guarantee that it will respond to received messages.
If a class receives a message that cannot be processed, the program will only throw an exception and will not make an error or crash.
In C++, the syntax for sending a message to an object (or calling a method) is as follows:
Obj.method (argument)
Objective-C is written as:
[obj method: argument]
These two styles have their own advantages and disadvantages. C++ forces all methods to have corresponding actions, and compile-time binding makes function calls very fast.
The disadvantage is that only the virtual keyword can provide limited dynamic binding capabilities. Objective-C is born with the dynamic binding ability of duck type.
Because messages are processed only at run time, unknown messages are allowed to be sent to the object. You can send messages to the entire collection of objects without checking the types of each object one by one
There is also a message forwarding mechanism. At the same time, the empty object nil defaults to doing nothing after accepting the message, so sending a message to nil does not have to worry about the program crashing.
String
As a superset of the C language, Objective-C supports conventions on C language strings. That is, single character quilt quotation marks include
The string is enclosed in double quotes. However, most Objective-C usually do not use C-style strings.
Conversely, most frameworks pass strings to the NSString object. The NSString class provides class wrappers for strings
Includes all the advantages you expect, including a built-in memory management mechanism for saving arbitrary length strings, and support for Unicode,printf-style formatting tools
Wait. Because such strings are used so frequently, Objective-C provides a mnemonic @ to easily create NSString objects from constant values.
As shown in the following example:
/ / create an Objective-C string from a C language string
NSString* fromCString = [NSString stringWithCString: "A C string"
Encoding:NSASCIIStringEncoding]
/ / use mnemonic @
NSString* name = @ "PANN"
NSString* line = [NSString stringWithFormat:@ "Hello,% s\ n", @ "String"]
Class (class)
Class is one of the most important concepts in object-oriented languages, and Objective-C also supports classes. The following figure is an introduction to a class declaration named MyClass:
Class.png
Statement
Following the specification of the C language, class declarations are generally defined in .h header files. The class declaration begins with the keyword @ interface and ends with @ end.
The + sign before the class method indicates the class method, and the-sign indicates the instance method. A corresponding C++ class is defined as follows:
Public MyClass: NSObject {
Protected:
Int count
Id data
NSString * name
Public:
Id intWithString (NSString * aName)
Static MyClass createMyClassWithString (NSString aName)
}
Realize
Following the specification of C language, the class implementation is generally defined in the corresponding .m file. Class implementation includes the implementation of exposed methods
And define private variables and methods. Start with the keyword @ implementation and end with @ end.
An implementation of the above class is as follows:
@ implementation MyClass {
NSString * secret
-(id) initWithString: (NSString*) aName {
Self.name = aName;return 0
}
+ (MyClass) createMyClassWithString: (NSString*) aName {
MyClass * my = [[MyClass alloc] init]; my.name = aName;return my
}
}
The property defined in the header file (class declaration) defaults to protected and the method is public. The property defined in the class implementation is private.
Of course, you can also use mnemonic characters such as @ public and @ private to override the default behavior.
Instantiation
Instantiation creates an object. Objective-C creates an object through two messages: alloc and init. The function of alloc is to allocate memory
Init is the initialization object. Both init and alloc are methods defined in NSObject. After the parent object receives these two messages and responds correctly,
The new object has just been created. As in the above category:
MyClass * my = [[MyClass alloc] init]
In Objective-C 2.0, if you don't need parameters to create an object, you can use new directly:
MyClass * my = [MyClass new]
Just a grammatical simplification, the effect is exactly the same.
To define the initialization process yourself, you can override the init method to add extra work. (constructor constructor for use similar to C++)
As follows:
(id) init {
If (self= [super init]) {/ / must call the init of the parent class
/ / do something here...
}
Return self
}
Method (method)
I have seen the definition and use of some methods when I introduced classes in the previous section. People who come into contact with Objective-C for the first time will find it strange (for example, I think this syntax is weirder than Golang).
But as long as you accept this setting, you can get used to it.
Statement
The following figure shows the insertObject method declaration of Objective-C 's built-in array type:
Method.png
The actual name of the method (insertObject:atIndex:) is the key cascade of all method identifiers, including colons. The colon indicates the appearance of the parameter.
If the method has no parameters, you can omit the colon after the first (and unique) method identification keyword. In this case, this method has two parameters.
This function is converted into a similar C++ representation as follows:
Void insertObject:atIndex: (id anObject, NSUInteger index)
Call
Calling a method is actually passing a message to the corresponding object. Here the message is the method identifier and the parameter information passed to the method.
All messages sent to the object are distributed dynamically, which facilitates the polymorphic behavior of the Objective-C class.
That is, if the subclass defines a method with the same identifier as the parent class, the subclass first receives the message
You can then optionally forward (or not forward) the message to his parent class.
The message is included in parentheses ([and]). The object that receives the message in parentheses is on the left, and the message and its parameters are on the right.
For example, to pass the message insertObject:atIndex: message to the myArray variable, you can use the following syntax:
[myArray insertObject:anObj atIndex:0]
Messages are allowed to be nested. That is, if you have a myAppObject object that has a getArray method to get an array
If there is a getObjectToInsert method to get the element, the nested message can be written as:
[[myAppObject getArray] insertObject: [myAppObject getObjectToInsert] atIndex:0]
Attribute (attribute)
There is nothing to say about attributes, similar to the class properties of C++. However, Objective-C 2.0 introduces a new syntax to declare variables as attributes
And includes an optional definition to configure the generation of the access method. Property is always public and its purpose is to provide external class access (or read-only)
The method of the internal variable of the class. Properties can be declared as "readonly", that is, read-only, or storage methods can be provided, including "assign"
"copy" or "retain" (simply assign, copy, or increase the reference count by 1). The default attribute is atomic
That is, a lock is placed on access to prevent multiple threads from accessing the same object at the same time, or the property can be declared as "nonatomic" (non-atomic)
Avoid producing locks.
Examples of defining attributes are as follows:
@ interface Person: NSObject {
@ public NSString * name;@private int age
}
@ property (copy) NSString * name
@ property (readonly) int age
-(id) initWithAge: (int) age
@ end
Synthesize
The access method of the property is implemented by the @ synthesize keyword, which automatically generates a pair of access methods from the declaration of the property.
Alternatively, you can choose to use the @ dynamic keyword to indicate that the access method is provided manually.
@ implementation Person
@ synthesize name
@ dynamic age
-(id) initWithAge: (int) initAge
{
Age = initAge; / / Note: directly assigned to member variables, not attribute return self
}
-(int) age
{
Return 18; / / Note: does not return the true age
}
@ end
Visit
Properties can be accessed using traditional message expressions, dot expressions, or "valueForKey:" / "setValue:forKey:" method pairs. As follows:
Person * aPerson = [[Person alloc] initWithAge: 53]
/ / modify attributes
APerson.name = @ "Steve"
[aPerson setName: @ "Steve"]
/ / read attributes
NSString * tmp
Tmp = [aPerson name]; / / message expression
Tmp = aPerson.name; / / Point expression
Tmp = aPerson- > name; / / directly access member variables
Tmp = [aPerson valueForKey:@ "name"]; / / property access
Protocol (Protocol)
A protocol is a list of methods that are not implemented, and any class can adopt the protocol and implement this set of methods. In short, it's the interface.
Can be compared to Java's interface, or C++ 's pure virtual function, to express a concept of is-a.
The protocol starts with the keyword @ protocol as the block, ends with @ end, and the middle is the method list. As follows:
@ protocol Mutex
(void) lock
(void) unlock
@ end
To declare the implementation of the protocol, you can use angle brackets as follows:
@ interface SomeClass: SomeSuperClass
@ end
Once SomeClass indicates that he has adopted the Mutex protocol, SomeClass has an obligation to implement two methods in the Mutex protocol:
@ implementation SomeClass
(void) lock {
/ / implement the lock method
}
(void) unlock {
/ / implement the unlock method
}
@ end
Dynamic type
Although Objective-C has dynamic typing capabilities, compile-time static type checking can still be applied to variables.
The following three declarations have exactly the same effect at run time, but they provide one more obvious type information than one.
The additional type information allows the compiler to check variable types at compile time and warn against variables that do not match.
The following three methods differ only in the shape of the parameters:
SetMyValue1: (id) foo
SetMyValue2: (id) foo
SetMyValue3: (NSNumber*) foo
The id type in Objective-C is similar to void pointers, but is strictly restricted to objects.
Message forwarding
After an object receives a message, he has three possible ways to process the message. the first is to respond to the message and run the method.
The message can be forwarded to other objects, and if neither of the above is available, an exception that cannot be answered will be dealt with. As long as one of the three
The message is discarded even if the task is completed. If you send a message to "nil" (null object pointer), the message is usually ignored
It's just that an exception may be thrown for some compiler options.
The Objective-C runtime defines a pair of methods in Object:
Forwarding method:
(retval_t) forward: (SEL) sel: (arglist_t) args; / / with GCC
(id) forward: (SEL) sel: (marg_list) args; / / with NeXT/Apple systems
Response method:
(retval_t) performv: (SEL) sel: (arglist_t) args; / / with GCC
(id) performv: (SEL) sel: (marg_list) args; / / with NeXT/Apple systems
The difference between GCC and NeXT/Apple compilers is that return values and parameter types are different.
Objects that want to implement forwarding only need to override the above method with a new method to define their forwarding behavior without overriding the response method performv::
Because the latter simply sends messages and passes parameters to the response object. Where the SEL type is the type of message in Objective-C.
Category (Category)
Objective-C borrows and extends the concept of "classification" in the Smalltalk implementation to help break up the code.
A classification can decompose the implementation of a method into a series of separate files. Programmers can put a set of related methods into a category
Make the program more readable. For example, you can add a category called "spell check" to the string class
And put the code related to spell checking into this category.
Methods in categories are added to classes at run time, a feature that allows programmers to add methods to existing classes
There is no need to hold the original code or recompile the original class.
For example, if the implementation of the string class provided by the system does not include the function of spell checking, such a function can be added without changing the code of the original string class.
At run time, the method in the classification is no different from the original method of the class, and its code can access all member variables, including private class member variables.
If the classification declares a function with the same name as the original method in the class, the method in the classification will be called. So classification can not only increase the methods of classes.
It can also replace the original method. This feature can be used to correct errors in the original code and fundamentally change the behavior of the original classes in the program.
If the methods in the two categories have the same name, the method being called is unpredictable.
The declaration of the classification is as follows:
@ interface ClassName (CategoryName)
@ end
Here is a concrete example of dynamically adding getCopyRightString methods to the NSString class through MyAdditions classification:
# import
@ interface NSString (MyAdditions)
+ (NSString *) getCopyRightString
@ end
@ implementation NSString (MyAdditions)
+ (NSString *) getCopyRightString {
Return @ "Copyright evilpan.com 2019"
}
@ end
Int main (int argc, const char * argv []) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]
NSString * copyrightString = [NSString getCopyRightString]
NSLog (@ "Accessing Category:% @", copyrightString)
[pool drain]
Return 0
}
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
Problem: all the virtual machines before
© 2024 shulou.com SLNews company. All rights reserved.