Object-oriented definitions, classes, and objects of the OBJECTIVE-C Foundation

Source: Internet
Author: User

1, the definition of the 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

  person.h//  classandobject////  Created by Kenshin Cui on 14-2-1.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h> @interface person:nsobject@end

Person.m

  person.m//  classandobject////  Created by Kenshin Cui on 14-2-1.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//#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";

2. 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.

  person.h//  classandobject////  Created by Kenshin Cui on 14-2-1.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//#import <foundation/foundation.h>//because NSObject is used, importing this header file//nsobject is the base class, The person implements the Nsobject@interface person:nsobject{/    * 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, whether a custom class or a system class object must be a pointer, such as the following _name/    @private    NSString *_name;//The recommended member variable name to begin with _ int in OBJC    _age;    @protected    nsstring *_nation;    @public    float height;} @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?

  main.m//  classandobject////  Created by Kenshin Cui on 14-2-1.//  Copyright (c) 2014 Kenshin Cui. All rights reserved.//#import <Foundation/Foundation.h> #import "Person.h" int main (int argc, const char * argv[]) { c4/> @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);//Result: 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;

2.1 The difference between member variables and attributes;

Summarize:

    • Member variables are used within a class, without the need for a variable to be exposed to outside.
    • Depending on the private nature of the member variable, the attribute variable is available for easy access. The advantage of a property variable is that it allows other objects to access the variable. Of course, you can set up read-only or writable, and the settings can be customized. Therefore, a property variable is a variable that is used to interact with other objects.

Some suggestions:
1. If it is purely a private variable, it is best to declare it in implementation.
2. If it is the public attribute of the class, it is written in the. h file.
3. If you need a setter and getter within yourself to implement something, declare it in the category of the. m file.

An instance variable between the curly braces {} in the. h interface, which can be used directly in. m;

The property variable in. h, which requires the use of the propertyvariable variable in the. M self.propertyvariable method

Below this program, Aboutlist, and otherlist exactly what is the difference,

@interface Othermain:uiviewcontroller

{

Nsmutablearray *aboutlist;

} @property (Nonatomic,retain) Nsmutablearray *otherlist;
Aboutlist is a private member variable, and other classes do not have access to this private member variable.
Otherlist is a property that is visible to all classes of the project, and other classes can be accessed to get this member variable. "But when to use the aboutlist, when to use the Otherlist!!!" ”
This class (Uiviewcontroller) is used with aboutlist or self. Otherlist, other classes to use the words used otherlist.

Attribute property in class

In the first version of iOS, we declare both the attribute and the underlying instance variable for the output, at which point the attribute is a new mechanism for the OC language and requires that you declare the instance variable that corresponds to it, for example:

@interface myviewcontroller:uiviewcontroller{    UIButton *mybutton;} @property (nonatomic, retain) UIButton *mybutton; @end

More recently, Apple has converted the default compiler from GCC to LLVM, which is no longer required to declare instance variables for a property. If LLVM discovers a property that does not have a matching instance variable, it automatically creates an instance variable that begins with the underscore. Therefore, in this version, we no longer declare instance variables for the export output.

Example: MyViewController.h file

@interface Myviewcontroller:uiviewcontroller@property (nonatomic, retain) UIButton *mybutton; @end

In the myviewcontroller.m file, the compiler will also automatically generate an instance variable, _mybutton. The _mybutton instance variable can be used directly in the. m file, or through the property Self.mybutton. It's all the same.

Note that the Self.mybutton here is actually the Getter/setter method that invokes the MyButton property.

For example, in OC there is the following code

. h file

@interface myviewcontroller:uiviewcontroller{    nsstring *name;} @end

An expression such as self.name is wrong in a. m file. Xcode will prompt you to use-> change it to Self->name. Because the OC midpoint expression represents the calling method, the above code does not have the name method.

OC syntax Description of the point expression: If the point expression appears on the equal sign = left, the setter method of the property name is called. If the point expression appears on the right, the getter method for the property name is called. "

So the expression in OC is actually a shortcut to the setter and getter method of the calling object, for example: Dealie.blah = greeble is equivalent to [Dealie.blah setblah:greeble];

In the previous usage, declare the attribute with the instance variable that corresponds to it:

@interface myviewcontroller:uiviewcontrolle{    UIButton *mybutton;} @property (nonatomic, retain) UIButton *mybutton; @end

This approach is mostly used, and most of it is now in use, since many open source code is this way. However, after the iOS5 update, Apple is recommended to use the following methods:

@interface Myviewcontroller:uiviewcontroller@property (nonatomic, retain) UIButton *mybutton; @end

Because the compiler automatically generates an instance variable _mybutton that starts with an underscore, you do not have to manually write the instance variable yourself. And there is no need to write @synthesize MyButton in the. m file; The Setter,getter method is automatically generated for you. @synthesize's role is to have the compiler automatically generate setter and getter methods for you.

@synthesize also has a role, you can specify an instance variable corresponding to the property, such as @synthesize MyButton = xxx; then Self.mybutton is actually the instance variable xxx of the operation, not _mybutton.

In the actual project, we generally write this. m file

@synthesize MyButton;

Once this is written, the compiler automatically generates MyButton instance variables, along with the corresponding getter and setter methods. Note: _mybutton This instance variable is not present, because the automatically generated instance variable is MyButton instead of _mybutton, so now the @synthesize function is equivalent to specifying the instance variable;

If @synthesize MyButton is written in the. m file, then the generated instance variable is MyButton, and if @synthesize MyButton is not written, then the generated instance variable is _mybutton. So there is a slight difference from the previous usage.

Ii. attribute property in category (not understood, pending)

Class is distinguished from the attributes that are added to the category, because only methods can be added to the category, and instance variables cannot be added. It is often seen in iOS code to add attributes to a category, in which case variables are not generated automatically. For example, the Uiviewcontroller class is extended in the UINavigationController.h file.

@interface Uiviewcontroller (Uinavigationcontrolleritem) @property (nonatomic,readonly,retain) Uinavigationitem * Navigationitem; @property (nonatomic) BOOL hidesbottombarwhenpushed; @property (Nonatomic,readonly,retain) Uinavigationcontroller *navigationcontroller; @end

The attributes added here do not automatically generate instance variables, and the attributes added here are actually added getter and setter methods.

Note that anonymous categories (anonymous extensions) can add instance variables, and non-anonymous categories cannot add instance variables, only methods, or properties (which are actually methods).

Object-oriented definitions, classes, and objects of the objective-c base

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.