Objective-C introduction to the Cocoa framework

Source: Internet
Author: User

Cocoa Framework is short for Cocoa. It is a fast Application Development (RAD, Rapid Application Development) Framework on Mac OS X and a highly object-oriented (Object Oriented) Development Framework. Whether you are a senior Mac developer or a new human entering the Mac development world, Cocoa is the Swiss army knife and Lego building block for your application development, it is the most powerful and efficient tool for building Mac OS X applications. It is worth mentioning that the reason why Apple is able to develop many top-level software is precisely because of the secret weapon of Cocoa. Cocoa is a native application development framework supported by Mac OS X. Apple strongly recommends it to all Mac developers.

Ashes topic: Hello World!

I believe that for any developer, Hello World! They should all be very familiar. So, Cocoa's Hello World! Do you understand the program?

 
 
  1. import 
  2.  
  3. int main (int argc, const char * argv[]) { 
  4.  
  5. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
  6.  
  7. NSLog(@"Hello, World!"); 
  8.  
  9. [pool drain]; 
  10.  
  11. return 0; 
  12.  

Hmm... can't you see it? Don't take a closer look? Still cannot understand?

Whether you understand it or not, first of all, like the vast majority of C programs you have seen, any Cocoa application has a primary function:

Int main (int argc, const char * argv [])

The main function is the main entry of the application and the place where everything starts and ends. Yes, that's right! On the surface, these codes are no different from the common C program code, and they are actually no different from the C program code.

Next you should ask me, What is Foundation? What is installed in Foundation. h? What is NSAID? What are the brackets ?...... Don't worry. In the following chapters, we will gradually familiarize ourselves with so many strange faces. Of course, I can give a rough explanation now:

The full name of Foundation Framework is a sub-development Framework of Cocoa. Foundation contains some of the most basic classes in Cocoa. They are generally responsible for Object Management, memory management, container and other related data structure operations in a Mac application. Foundation. h is the header file of Foundation. Once this header file is introduced, we can use any class declared in Foundation in our own program. For example, in the above Code, the nyothoreleasepool is a class declared in Foundation, which provides applications with controllable memory management for the release of delayed objects. As for square brackets, they are the most basic syntax in Objective-C. The content in a pair of square brackets indicates a method call to an object (or class.

If you do not understand it, please do not panic. Let's talk about it in the following chapters. In addition, Cocoa's International Phonetic Alphabet is ['koukou], hoping that everyone can read the audio of this word.

I am actually very C

When using Cocoa for application development, Objective-C is our preferred language. (Of course, Cocoa also builds bridges in programming languages such as Cocoa-Ruby and Cocoa-Python through official and third-party channels, enables developers from both Ruby and Python to quickly get started using languages they are familiar .) However, here, we still need to first promote Objective-C as a Cocoa program development language for two reasons:

1. Objective-C is actually a superset of C.

The Runtime Library of Objective-C is completely written by C. Therefore, any Objective-C Message distribution (Message Dispatching ), will be replaced with the call of one or several C functions in the Objective-C runtime environment. This mechanism provides Objective-C with efficient message distribution and full native compatibility with C code.

Second, the entire Cocoa Framework is implemented by Objective-C/C.

Therefore, when developing a Cocoa application, Objective-C is our best choice.

When talking about "Objective-C", although the programming model is different from C, although the syntax seems a bit strange, we still discuss the C language. Because Objective-C is indeed C, it is easier to say:

Objective-C is a C with an Object-Oriented Layer. The Objective-C evolved from Smalltalk to support this object-oriented layer. Therefore, if you are using Objective-C to develop a Cocoa application and want to insert some C code in some places of some code, please rest assured to continue!

Deep design patterns: ubiquitous MVC

In the traditional development mode, we can easily fall into the trap of "glue Code. The so-called "glue code", as its name implies, is a collection of function calls that are only used to maintain user interface data and State synchronization. These functions are constantly called, and the logic is still messy, and the code becomes very lengthy, error-prone, and difficult to maintain.

To solve this problem, Cocoa provides multiple internal mechanisms: Key-Value Coding (KVC), Key-Value Observing (KVO), and Key-Value Binding (KVB ). These mechanisms define a set of common Cocoa naming rules and call rules to implement the following functions:

1. use a highly normalized access method to obtain and set the value of any attribute of any object (the so-called attribute can be a real member variable, it can also be a property of the object abstracted by a pair of member methods ).

2. by inheriting a specific method and specifying the object to be monitored and the name of the attribute to be monitored, you can change the value of the specified attribute of the object, get a "notification" (although this is not a real notification) and get a change in the value of the relevant attribute (the original value and the new value after the change ).

3. A simple function call ensures that a specified attribute of a view object is synchronized with a specified attribute of a controller object or model object anytime, anywhere.

A developer can use these functions to write the classes they have created in a very standard and common manner, and then use KVB to "bind" multiple views to one or more controllers, then, bind the Controller to the bottom-layer data model. In this way, any changes to the view will be "pressed" to the Controller through KVC, and then "pressed" from the Controller to the data model through KVC. When the value in the data model changes, one or more controllers will receive "notifications" From KVO ", then, as long as the view is bound, the KVO "notification" of one or more controllers will be obtained ". In this way, developers only need to tell Cocoa when appropriate, what object value and what object value should be bound, cocoa will update and format other data for you.

Is it convenient?

One of Easy Life: Memory Management

Memory Management is a big problem for many developers. In Cocoa, memory management is done by referencing the counter model.

Each object in Cocoa has a reference counter to maintain its own lifecycle. Whenever an object needs to "use" or "Occupy" another object, it sends a retain message to the object to auto-increment the reference counter of the object, when the object is no longer needed (or used up), it sends a release message to the object to subtract the reference counter of the object. When the reference counter of an object is reduced to zero, the object will be released.

Here is an example:

 
 
  1. NSString *aString = [[NSString alloc] initWithString:@"This is a demo."]; 

This Code creates an NSString object and initializes it. When an object is created, its reference counter is set to 1. Therefore, if you no longer need this object, you only need to directly send the release message to it, and it will be directly analyzed. When you need to use this NSString for other code blocks, you can call this NSString object once to add its reference counter:

[AString retain]; at this time, its reference counter value is 2. When you use this object, if you call the retain for this object, you should call the release symmetric once. In this case, a basic programming specification is called "who retain, who release ".

 
 
  1. [aString release]; 

After the call, the reference counter returns to 1 again. Finally, when we do not need this object completely, we can do this:

 
 
  1. [aString release]; 
  2.  
  3. aString = nil; 

In the previous two lines of code, the first sentence will be responsible for the NSString object structure, and the second sentence will be responsible for "returning to zero" the pointer (NSString * aString) originally directed to this NSString object ", this is because the "wild pointer" may cause exceptions and crashes in your program at any time.

Is it easy?

Of course, there are also a little complicated cases. In the beginning, we mentioned a class called the NSAID utoreleasepool, right? The nyothoreleasepool is an important part of the Cocoa memory management mechanism. We often encounter this problem on the premise that the object "who retain, who release" is used, that is, we want to return an object created locally:

 
 
  1. (NSString)demoString 
  2.  
  3.  
  4. NSString *result = [[NSString alloc] initWithString:@"This is a demo."]; 
  5.  
  6. return result; 
  7.  

Under the principle of "who retain, who release", the above Code is obviously only responsible for retain (alloc call is equivalent to retain), but not for release, therefore, such writing may cause memory leakage because the code segment that calls this method (or this API) does not know whether to release the return value of this method (or this API.

But if we release it directly:

 
 
  1. (NSString)demoString 
  2.  
  3.  
  4. NSString *result = [[NSString alloc] initWithString:@"This is a demo."]; 
  5.  
  6. [result release]; 
  7.  
  8. return result; 
  9.  

Then return will be a "wild pointer" (or if you are clean enough, return will be a zero pointer), not the value we need. Therefore, we need a mechanism that can delay release and automatically release. As a result, people invented another wheel called the NSAID utoreleasepool, and the Code became like this:

 
 
  1. (NSString)demoString 
  2.  
  3.  
  4. NSString *result = [[NSString alloc] initWithString:@"This is a demo."]; 
  5.  
  6. [result autorelease]; 
  7.  
  8. return result; 
  9.  

After an object is sent with autorelease, the object will not be immediately released, but will be "registered" to the same NSAID utoreleasepool object closest to it. When the NSAID utoreleasepool is cleared or released, the "registered" object will be actually sent a release message.

Easy Life 2: Container

Containers are something that most programmers love and hate. In Cocoa, containers are so easy to use that once you have used them, they will be "Easy to use ". The container classes in Cocoa mainly include NSString, NSArray, NSDictionary, NSSet, and NSIndexSet. They are all part of the Foundation Framework.

Why do people love Cocoa containers?

Cause 1: NSArray, NSDictionary, and NSSet do not force consistency of their internal element types. A simple example:

NSString * aString = [NSString stringWithString: @ "This is a demo."];

NSNumber * aNumber = [NSNumber numberWithInteger: 0];

NSArray * anArray = [[NSArray alloc] initWithObjects: aString, aNumber, nil];

In the above example, we first create an NSString object, and then create an NSNumber object. Finally, we "plug" these two NSString and NSNumber objects into an NSArray object.

Is it refreshing? Don't even think about it. Everything can be installed in it (except for basic types and struct )!

Cause 2: "modifiable" and "unchangeable" of the container class"

The NSString, NSArray, NSDictionary, NSSet, and NSIndexSet shown above are all "unchangeable" versions of the container. The so-called "unchangeable" means that once the container is created, we cannot modify its set through code. What should we do if we need to modify the elements of these containers (such as adding, deleting, and replacing?

Almost all container classes in Cocoa provide another "modifiable" version. For example, NSMutableString inherited from NSString, NSMutableArray inherited from NSArray, NSMutableDictioanry inherited from NSDictionary, NSMutableSet inherited from NSSet, and NSMutableIndexSet inherited from NSIndexSet. These "modifiable" versions provide a simple and intuitive way to modify its internal elements. For example:

 
 
  1. NSString *aString = [NSString stringWithString:@"This is a demo."]; 
  2.  
  3. NSNumber *aNumber = [NSNumber numberWithInteger:0]; 
  4.  
  5. NSMutableArray *aMutableArray = [NSMutableArray array]; 
  6.  
  7. [aMutableArray addObject:aString]; 
  8.  
  9. [aMutableArray addObject:aNumber]; 
  10.  
  11. [aMutableArray removeObjectAtIndex:0]; 
  12.  
  13. [aMutableArray removeAllObjects]; 

In the above Code, lines 1 and 2 create an NSString object and an NSNumber object. The third row creates an NSMutableArray object (that is, an "modifiable" NSArray object ). 4. Use the-addObject method to add the NSString object and NSNumber object created in the first and second rows to the "modifiable" NSArray. The sixth row deletes the first element in the Array Based on the given index number 0. In row 7, removeAllObjects deletes all elements in the array (empty array ).

Does it make everything easier?

Pick up Xcode and enjoy the joy of Cocoa programming!

Cocoa for fans

"Simple things simple, complex things possible." (Simple things are simpler and complex things are also possible .)

"C ++ is to C as Lung Cancer is to Lang." (C ++ is to C, just as Lung Cancer is to Lung .)

"We thought we wocould see how hard it wocould be to switch the code we had to use Cocoa Bindings. we rewrote everything in a day or two-I think we deleted over a thousand lines of code that just wasn't needed any more. (we thought it was very hard to migrate the original code to the code using Cocoa Bindings. But in fact we have rewritten everything in just one or two days-I think we have deleted more than one thousand lines of code that are no longer needed because of Cocoa Bindings .)

"Without Cocoa Bindings, it wocould have taken another four or five months, maybe more, to finish Delicious Library. "(if there is no Cocoa Bindings, it may take another four or five months to complete the Delicious Library .)

"With Cocoa, we were able to accomplish a lot more, more quickly." (With Cocoa, we can implement more and more quickly .)

"I want to marry Core Data and have its children." (I want to marry and have children with Core Data .)

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.