Dark Horse Programmer---objective-c basic learning---classes, objects, methods related knowledge notes

Source: Internet
Author: User

------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------

Class, object, method related knowledge notes

Objective-c has object-oriented features relative to C, but OBJC has no other grammatical features of object-oriented language, and OBJC itself streamlines object-oriented. Here are some related knowledge notes.

    1. Class definition
    2. Member variables
    3. Methods and properties
    4. Self keyword
Class definition

Defining a class in C #, Java, and other high-level languages is fairly straightforward, and a single keyword class with a pair of curly braces is basically done, but the definition of the class in the OBJC is relatively different. Now suppose you need to define a person class

Add files in Xcode, choose Cocoa Class or Cocoa Touch class

Enter the class name person and select the parent class as NSObject

The following two files are generated by default

Person.h

#import <Foundation/Foundation.h>@interface  person:nsobject@end

Person.m

#import " Person.h " @implementation  Person @end

Defining a class in OBJC requires two files. h and. M:

    • . h file: A declaration of a class, including member variables, properties, and method declarations (in fact. h files do not participate in the compilation process); Keyword @interface declares a class, and it must end with @end, declaring the relevant member in the middle of these two keywords In declaring the person class, you can see that it inherits from NSObject, which is the base class of OBJC, and all classes eventually inherit from this class (but note that there is not only one base class or root class in OBJC, for example, Nsproxy is also the base class for OBJC). Since this class is defined in the foundation framework, <Foundation/Foundaton.h> is imported (meaning that the Foundation.h declaration file is imported into the foundation framework);
    • . m file: The implementation of the attribute, the method, the keyword @implementation is used to implement a class, at the same time must end with the @end, in the middle of these two keywords to implement specific properties, methods; Because the person class is used in. m, you need to import the declaration file "Person.h";
Member variables

Suppose that the person class contains the name, age, Ethnicity (nation), height (height) Four member variables, while the name and age of two member variables are private, height is public, and the nation is restricted to only subclasses can access.

#import<Foundation/Foundation.h>//import this header file because NSObject is used//NSObject is the base class, and the person implements the NSObject@interfaceperson:nsobject{/*The member variable must be enclosed in curly braces * Note that member variables that do not declare any keywords are the default accessibility @protected * Note that in OBJC, either a custom class or a system class object must be a pointer, such as the following _name*/    @privateNSString*_name;//recommended member variable names start with _ in OBJC    int_age; @protectedNSString*_nation; @public    floatheight;}@end

Member variables are defined in the. h file and must be defined within {} after the class. The accessibility of a member is declared by the following three keywords:

    • @private Private member, only the current class can be accessed;
    • @protected protected member, only the current class or subclass can be accessed (default is @protected if no adornments are added);
    • @public public members, all classes are accessible;

Accessibility modifiers in OBJC In addition to these three kinds, there is also a @package less commonly used, it is similar to C # internal in the framework is public, but outside the framework is private (that is, can only be accessed within a framework). So since height is public, how can the outside world access it?

#import<Foundation/Foundation.h>#import "Person.h"intMainintargcConst Char*argv[]) {@autoreleasepool { person*p=[Person alloc]; P=[P init]; //The above two lines can be written directly: Person *p=[[person alloc] init]; //can also be written as: Person *p=[person new];P->height=1.72; NSLog (@"height=%.2f", p->height);//results: height=1.72    }    return 0;}

Here are a few things to note:

    • All variables of the object type in the OBJC must be prefixed with "*", and in ObjC the object is actually a pointer (for example, NSString, as seen previously, but the basic type does not have to be "*");
    • Using [] in OBJC, the essence of a method call in OBJC is to send a message to the object or class;
    • It takes two steps to instantiate a class in OBJC: allocating memory, initializing;
    • The initialization of the class calls the Init method of the parent class, and if initialized with the default initialization method (no parameters), memory allocation and initialization can be simply written as [person new];
    • Public member invocation using the "-" operator;
Methods and properties

Now that you have the above member variables, suppose you need an object method to set the user's name, and a class method to print some information.

In ObjC, the method is divided into static and dynamic methods, the dynamic method is the method of the object, static method is the class method, which is no different from other high-level languages. Use "-" in OBJC to define dynamic methods, and "+" to define static methods. If a method has a declaration in. h, the method is a public method, and if it is not declared in. h directly defined in. m, the method is private and cannot be accessed externally.

Person.h

#import<Foundation/Foundation.h>//import this header file because NSObject is used//NSObject is the base class, and the person implements the NSObject@interfaceperson:nsobject{/*member variables must be enclosed in curly braces * Note that member variables do not declare any keywords to be @protected, others have @private and @public * Note that in OBJC, either a custom class or a system class object must be a pointer, such as the following _name */    @privateNSString*_name;//recommended variable names start with _ in OBJC    int_age; @protectedNSString*_nation; @public    floatheight;}//declares a dynamic method with no return value-(void) SetName: (NSString *) name;//declares a static method with no return value+(void) ShowMessage: (NSString *) info;@end

Person.m

  #import  "     @implementation   person  //  Implement a dynamic method -(void ) SetName: (nsstring *) name{_name  = //  + (void ) ShowMessage: (nsstring *) info{NSLog ( @ " %@   ,info);}   @end  

In OBJC, the parameter type of the method, the return value type needs to be placed in (), and the parameter must be preceded by a colon, and the Colon is part of the method name . Of course, the above method has only one parameter, assuming that there is now a way to set the age and place of origin, can be written as follows:

-(void) Setage: (int) Andheight: (NSString *) nation{    _age= age;    _nation=Nation;}

Where andheight can be omitted to write, of course, in order to ensure that the method name more meaningful to write when adding.

As you all know, the concept of attributes is often mentioned in other languages, and usually a member's access is not passed directly through the member variable but through the attribute burst to the outside world. In OBJC, the implementation of attributes is similar to that of a property definition in Java, implemented by the corresponding setter and getter methods. Yes, the above setname is actually the setter method of the property, but in OBJC the Gettter method usually uses the variable name instead of "get". Let's look at the implementation of the age attribute

Person.h

#import<Foundation/Foundation.h>//import this header file because NSObject is used//NSObject is the base class, and the person implements the NSObject@interfaceperson:nsobject{/*member variables must be enclosed in curly braces * Note that member variables do not declare any keywords to be @protected, others have @private and @public * Note that in OBJC, either a custom class or a system class object must be a pointer, such as the following _name */    @privateNSString*_name;//recommended variable names start with _ in OBJC    int_age; @protectedNSString*_nation; @public    floatheight;}//declares a dynamic method with no return value-(void) SetName: (NSString *) name;//declares a static method with no return value+(void) ShowMessage: (NSString *) info;//declaring Age's setter, getter method-(int) age;-(void) Setage: (int) age;@end

Person.m

#import "Person.h"@implementation Person//implement a dynamic approach-(void) SetName: (NSString *) name{_name=name;}//Private Methods-(void) Setage: (int) Age Andheight: (NSString *) nation{_age=Age ; _nation=Nation;}//implement a static method+(void) ShowMessage: (NSString *) info{NSLog (@"%@", info);}//implements the setter, getter method for age-(int) age{return_age;}-(void) Setage: (int) age{_age=Age ;} @en
//Here is a specific call
#import<Foundation/Foundation.h>#import "Person.h"intMainintargcConst Char*argv[]) {@autoreleasepool { person*p=[Person alloc]; P=[P init]; //The above two lines can be written directly: Person *p=[[person alloc] init]; //can also be written as: Person *p=[person new]; //member variable invocationp->height=1.72; NSLog (@"height=%.2f", p->height);//results: height=1.72//Method Invocation[P SetName:@"Kenshin"]; //Property CallP.age= -;//equivalent to: [P setage:28]; intAge=p.age;//equivalent to: age=[p age];NSLog (@"age=%i", age);//results: age=28 } return 0;}

We can see how p.age is called, is not similar to C #, Java in the invocation of properties, this is the point syntax in OBJC. In fact, the essence of this method of invocation is to call the corresponding method for processing, so that the purpose is only for developers to write convenience (this is the purpose of syntactic sugar). Whether P.age is calling the Get method or calling the set method depends entirely on whether the current operation is an assignment operation or a read operation.

We can see from the above program that if you want to define a property, you first need to declare it in. h and then implement it in. m, and the code that defines the property is basically similar.

Self keyword

In C #, Java, there is a keyword this is used to represent the current object, in fact, there is a similar keyword self in objc, just can not only indicate that the current object can also represent the class itself, that is, it can be used in static methods and can be used in dynamic methods.

Perosn.h

#import <Foundation/Foundation.h>@interface*int age ; -(void) SetName: (NSString *) name andage: (int) age; + (void) showmessage; @end

Person.m

#import "Person.h"@implementation Person-(void) SetName: (NSString *) name Andage: (int) age{//_name=name;//_age=age;Self.name=name; Self.age=Age ;}+(void) printinfo{NSLog (@"hello,world!");}+(void) showmessage{[self printinfo];}@end

Main.m

  #import  <foundation/foundation.h> #import   person.h   " int  Main (int  argc, const  char  * argv[]) {person  *p=< Span style= "color: #000000;"    >[[person Alloc]init]; [P SetName:  @ " kenshin   andage:28      return  0  ;}  

You can see the setname:andage in the code above : The method is a dynamic method, where self represents the calling object, and in the ShowMessage method, the self invokes the static method Printinfo of the class, at which time the self represents the calling class Therefore, it can be concluded that self in OBJC represents the caller of the current method.

Dark Horse Programmer---objective-c basic learning---classes, objects, methods related knowledge notes

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.