The definition of---Class of OC learning article

Source: Internet
Author: User

We have previously introduced a program helloworld:http://blog.csdn.net/jiangwei0910410003/article/details/41578003 in OC, and today we continue to learn about classes in OC.

The biggest difference between OC and C is the object-oriented function, so when it comes to object-oriented, we have to say the concept of class, if you learn Java, then the concept of classes and objects is not unfamiliar, because Java is a very pure object-oriented design language. The concept of classes and objects is not carefully described here, there are various interpretations on the Internet. Let's open up. How to define a class in OC, how to instantiate an object, and so on.

First we build a new project, the system will automatically create the main.m file, this time, we right-click the project, select New file.


Then select source in OS X, select Cocoa Class and click Next


Click Next


Here is the name of the following class, which is similar to that in Java, click Next:


We can see that a new person class is created, but this is a bit different from Java, a class is made up of two parts, one is the header file of the class Person.h (which is usually done in this file), There is also a person.m file, which is generally implemented as defined in the header file. This is also a continuation of the C language of the project structure it. General header files are only responsible for defining functions, and. c files are responsible for implementing specific functions. It's similar here.

Here's a look at the definition format for the class in the Person.h header file:

//person.h//02_classdemo////Created by Jiangwei on 14-10-10.//Copyright (c) 2014 Jiangwei. All rights reserved.//#import <Foundation/Foundation.h> @interface person:nsobject{//Define a property (global variable/instance variable) in {}//Note  Meaning: can only be defined can not be assigned value, because this is only in the declaration operation, cannot assign the value of the//underline, in order to distinguish the local variable nsstring *_name;//name, the default value is nil: null pointer, you can view the definition: #define NIL NULL Nsinteger _age;//age, the default value is 0}//definition method//-: Instance method, +: Class method//Format: Method description (return type) method name: (parameter type) parameter name//Note method name is shopping:, not shopping, this should be noted-(void) Shopping: (float) price;//Definition Method Set property value (note setxxx)-(void) SetName: (NSString *) name;-(void) Setage: (Nsinteger) age;// Defines the method's Get property value (note that it is not a getxxx, but a direct property name, because GetXXX has other uses in OC)-(NSString *) name;-(Nsinteger) age;//method definitions for multiple parameters// The method name consists of two parts: setname:setage:-(void) SetName: (NSString *) name Setage: (Nsinteger) age;//or method name: SetName::, the following can be omitted, However, it is not recommended to use//-(void) SetName: (NSString *) name:(Nsinteger) age;//class method//The property is inaccessible in this method because the property belongs to the object, not the class's + (person *) Newperson; @end

The keyword that first sees the definition of the class is:

@interface


The general class is defined in the following format:

@interface Class Name: nsobject{

Defining properties

}

Defining methods


Here are a few things to note:

1, any class in OC is inherited NSObject, this and the Java object is a concept, so here need to import

#import <Foundation/Foundation.h>

In fact, the object objects in Java are in the java.lang.* package, but Java does not import this package because the class loader of the object class does not need to be imported.

2. The inheritance symbol here is the same as in C + +, using a colon :

3, in the {} class to define the properties of the class, about the properties described here and in Java is not a concept, in OC as long as the field defined in {} is the property of the class, and Java is a getxxx/setxxx method, is called a property. It is also important to note that the attribute names defined in the class in OC are underlined: "_" begins, why do you want to do this, just to distinguish the next local variable with its name, of course, we generally in Java in the beginning of M, or other way, Java is not so strong specification, But OC is strongly recommended in this way, there is a point to note, in the definition of the setting method, the general style is setxxx, but in the definition of the value of the method is directly xxx, rather than getxxx, this is also different from Java, as for why so, Because the Get Start method has other uses, it will be said later. Just pay attention to it here.

4, after the definition of the attribute is a simple definition method


Here is a look at how to define a method:

The definition method in OC differs greatly from the Java language, so it is difficult to remember, if not used, to look at the definition format of the method:

Method Description ( return type ) method name : ( parameter type ) parameter name


1. There are two ways to explain the method:

One is a minus sign: "-", which means that the method is an object method, that is, an object instance must be used to invoke the

One is the plus sign: "+", which means that the method is a class method, which can be called directly from the class, and does not need to instantiate the object, similar to the static method in Java

2, return type: This is simple, and the Java language is very similar

3. Method Name: Method name is not the same as in Java, look at an example:

Note that the method name is shopping:, not shopping, this should be noted-(void) Shopping: (float) Price;
The method name of this method is shopping: It contains a colon, and then look at an example:

The method definition//method name of multiple parameters consists of two parts: setname:setage:-(void) SetName: (NSString *) name Setage: (Nsinteger) age;
Multi-parameter method definition, then the method name of the method is setname:setage:

4, (parameter type) parameter name: This is also very different from Java, and it feels like the opposite of what is defined in Java, and he encloses the type with parentheses. The object types in OC are different from those used in Java, and it is important to note that the object type in OC is equivalent to the pointer definition style (class name *) in C.


Of course @end keyword is used at the end of the class definition


After reading the definition of the class, here's a look at the concrete implementation of the class:

Person.m

  person.m//  02_classdemo////  Created by Jiangwei on 14-10-10.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "Person.h" @implementation person//Implementation Method-(void) Shopping: (float) price{    NSLog (@ "%@ Shopping%f ", _name,price);} -(void) SetName: (NSString *) name{    _name = name;} -(void) Setage: (nsinteger) age{    _age = age;} -(NSString *) name{    return _name;} -(Nsinteger) age{    return _age;} -(void) SetName: (NSString *) name Setage: (nsinteger) age{    _name = name;    _age = age;} + (person *) newperson{    return [[Person alloc] init];} @end
see the implementation of the class using the @implementationKey Words

In the implemented source file, you must import the header file of the class's definition

#import "Person.h"

such a form is very similar to the engineering structure in C language.

Then there are the specific implementations of some of the methods defined in the header file, and in the implementation file, we can access the properties defined in the class. The rest is no more difficult, it is not in detail, the same class of the end of the flag:@end

class definition and implementation are all done, let's look at how to use this:

Main.m

main.m//02_classdemo////Created by Jiangwei on 14-10-10.//Copyright (c) 2014 Jiangwei. All rights the definition of the reserved.////class is placed in the. h File//class implementation in the. m file//define a class's steps//define the class name, write the class's properties, write the class's behavior #import <foundation/foundation.h        > #import "Person.h" int main (int argc, const char * argv[]) {@autoreleasepool {//Create object//Request a piece of memory area in memory        Person *person = [Person alloc]; Call the initialization method, initialize some default data//may have been used before the memory requested above, and there will be previous data.                So we need to empty the data, and the default value will be assigned (the equivalent of the empty operation)//person = [person init]; Merge//apply for two pieces of memory here: One is the object pointer variable, one is the ALLOC request//You can see the Alloc/init method is a class method, you can view the definition of nsobject object person *person = [[Pe                Rson alloc] init];                There is another way to create an object, but this approach is not recommended because it is equivalent to putting the above two merges//sometimes we need to separate the above two steps//person *person1 = [person new];                Set the name [person setname:@ "Jaingwei"];                Call instance method shopping [person shopping:200];        Person *person1 = [[Person alloc] init]; [Person1 SetName: @ "Huangdaoyang"];        [Person1 shopping:300];                Setting the value of two properties at the same time, but not recommended in this way, we recommend using the Set method [Person1 setname:@ "Huangdaoyang" setage:22];        Get method call NSString *person_name = [person name];        NSLog (@ "name is%@", person_name);        NSString *person1_name = [person1 name];                NSLog (@ "name is%@", person1_name);        class method calls person *person2 = [person Newperson];        [Person2 setname:@ "Shixin" setage:22];                [Person2 shopping:400];        Null pointer person *person3 = NIL;                    No action is taken, but the null pointer exception is not error [Person3 setname:@ "Empty object" setage:22]; } return 0;}
the way an object is instantiated in OC is:

Person *person = [[Person alloc] init];
The first is the pointer type of the style to define a variable, and then call the Alloc method of the class, and then call the Init method, here is a bit more strange, when we define the person class, there is no definition of the Alloc and Init method, why not error here? This is similar to Java, because any class in OC is integrated NSObject class, then naturally think of these two methods are nsobject defined. And we can see that the Alloc method is a class method, and Init is the object method

At the same time, the method invocation mode in OC:

Object method: [object variable method name parameter]

Class method: [Class name Method name parameter]

There is a big difference between instantiating an object and Java, and the new one in Java is fine. Here we need to call two methods Alloc and Init

As you can understand: Alloc is the equivalent of allocating memory space to this object, and Init is the constructor that calls this class to initialize properties and fields

Of course, the above instantiation can also become a two-step operation:

Person *person = [person alloc];//calls the initialization method, initializes some default data//may have been used before the memory requested above, and there will be previous data. So we need to empty the data, and the default value will be assigned (equivalent to vacuuming) person = [person init];
But the way it is suggested in OC is the above.

The invocation of the object method, setting the name:

Set the name [person setname:@ "Jaingwei"];

Multiple parameters of an object method call, setting both the name and age

Setting the value of two properties at the same time, but not recommended in this way, we recommend using the Set method [Person1 setname:@ "Huangdaoyang" setage:22];


the invocation of the class method:

class method calls person *person2 = [person Newperson];


Summarize

Well, about the definition and implementation of the class in OC, how to use it is introduced here, we can learn in the process and an object-oriented language compared to learning, which may be learned quickly.

The definition of---Class of OC learning 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.