Dark Horse programmer _ios Development _objective-c Learning Notes _ Class (object)

Source: Internet
Author: User

1. Basic introduction to Object-oriented programming:

Object-Oriented Programming (English: object-oriented programming, abbreviation: OOP), refers to a programming paradigm, and is also a method of program development. An object is a collection of classes, which are templates of objects that encapsulate objects as the basic unit of a program, encapsulating programs and data to improve the security, reusability, flexibility, and extensibility of the software.

2. Object-oriented and process-oriented

process-oriented is to analyze the steps required to resolve the problem, and then follow these steps to implement the steps step-by-stage with code and functions.


Object-oriented is to decompose the constituent issues into individual objects, and then each object to deal with the related program functions, the programmer does not care about the concrete implementation of the object, only need to know how to use the interface code, greatly enhancing the reusability of the code.

3. Object or Class

A class is a template for an object, and a class-based template can generate a large number of similar objects, and an object is an instantiation of an abstract class.

Classes in Objective-c in 4.IOS development

4.1structure of OBJECTIVE-C class

Extended Name File type description
. h header file/declaration file. Header files contain classes, types, functions, and constant declarations, and the declaration of a class uses keywords @interface and @end . UI design, control outlet and action in storyboard are dragged into the H file of Uiviewcontrol
. m implementation files. Files with this extension can contain objective-c code, sometimes referred to as source files, and the implementation of classes using keywords @implementation and @end .

The member functions in the Note:h file simply make a declaration and do not implement the method. That is, it simply explains the method name, the return value type of the method, the type of parameter the method receives, and does not write code inside the method. In order to #import the H file, the system will automatically recognize what we want to enter, with code reminders.

4.2 Methods

+ Denotes class method
– Represents an object method


All method scopes declared in. h are of the public type.

The difference between a class method and an object method is that a class method cannot use a member variable

The main reason for using class methods is that you do not need to instantiate an object and you can use the method, and when the method does not need to access the class's member variables, consider defining the method as a class method

5. Create a class5.1 statement :

All of the classes in iOS development are inherited from NSObject. The class declaration begins with the compiler directive @interface, ending with a @end instruction. After the class name, separated by a colon, is the name of the parent class. In Objective-c, a class can have only one parent class.

Write declarations of properties and methods between @interface directives and @end directives. These declarations make up the public interface of the class. Semicolons mark the end of each property and method declaration. If other custom functions, constants, or data types, place their declarations on the @interface ... @end block above.

In note:objective-c we usually precede the member variable with _ (underscore) to distinguish it from other variables, where there are three types of member variables, namely @public, @protected, @private, if no type is specified, The default is @protected.

A method declaration contains a method type identifier, a return type, one or more signature keywords, and parameter type and name information.

The name of a method (for example: insertObject:atIndex: ) is a concatenation of all the signed keywords, including the colon character. A colon character indicates that a parameter exists. In this example, the method takes two parameters. If the method has no arguments, the colon is omitted.

5.2 Implementation :
The class implementation starts with a @implementation instruction and ends with a @end instruction. The middle is the method implementation.

Here is an example code

#import " Person.h " @implementation Person-(ID) initwithstring: (NSString *) name{//  Insert your code }+ (Person *) Personwithstring: (NSString *) name{//  Insert your code }@end

6. Instantiating an Object
#import <Foundation/Foundation.h>#import"Person.h"int Main (intconstChar *person//) Allocates memory space for object and initializes   return0;}

Alloc: Returns the person object with the memory assigned to it, with a pointer to the person type on the left of the equal sign to receive the object,
Init: Object Initialization

Note: You can also write this in the following way, but it is not recommended

New];

7. Releasing objects

Programmers need manual memory management before older versions, which means releasing objects to write code themselves.
[class release] , class is the object that we instantiate above.

However, in Xcode5.0, the system is enabled by default arc (full name: Automatic Reference counting) mechanism, at this time the task of releasing the object is referred to the system, if you are using version 5.0, and want to manually release the object, you can in the build Settings found Apple LLVM 5.0–language–objective C below set the value of Objective-c Automatic referencecounting to No.

Otherwise, Xcode will make an error when you use release.

8. Dot Syntax

Here we add two methods to the person class:

    1. - (int)age;
    2. - (void)setage:(int)age;

1, the above age is Getter method, OC is accustomed to the getter method named and instance variable name.
2, the above setage is the setter method, is also used to start with the set, and the following is also the same as the instance variable name, and the first letter to uppercase.

In addition to the above method, OC also provides a point syntax for accessing the class method, see Example

// using OC syntax, access the Getter method of age, setter method [PErson age ]; [P Erson setage:[];
// use point syntax to access the Getter method of age Person . Age Person ;

The point here is that person.age equals [person age],person.age = 28 equals [Person setage:28],. Syntax is actually a getter and setter method for accessing object methods. The exact method you use depends on your personal preference.

9. Construction method

In Objective-c, Init is the default construction method.

In general, the classes we write may be assigned to the object variables at initialization time, so we'll refactor the construction method, as shown in the following example code:

// declaration -(ID) Initwithperson: (int) age; // implementation -(ID) Initwithperson: (int=if=  return Self ;}

As we can see from the code above, the return value type of the constructed method is Id,id understood as any type of type.
The above uses [Super Init], which is called the parent class Init method to initialize, and returns the assignment to the current object, self, and then determine whether it is true, if it is _age assignment, otherwise do nothing, and finally return the current object self;

If we refactor the constructor , we can create the object using the following method and initialize it.

Person *person = [Person Initwithperson:];

10.Self keywords

The self in OBJECTIVE-C represents the caller of the current method.

-(void) test1 () {[Self test2];} + (void) test2 () {[Person test1]; [Self test1];}

From the above code we can see that in both the class method and the object method, you can use the Self keyword to call other methods, and equal to [person test1] this way.

If you subdivide it, it can be understood as:
Class method: Self represents this class.
Object method: Self represents this object.

11. Null pointer and wild pointer

11.1 NULL pointer
A pointer that does not store any memory address is called a null pointer (a null pointer)
A null pointer is a pointer that is assigned nil and has a value of nil before it is specifically initialized.
All two of the following are null pointers:

    1. Student *S1 = NULL; Note:null is a C-language notation.
    2. Student *s2 = nil; Note:nil is the language of OC

11.2 Wild Hands
"Wild Pointer" is not a null pointer, it is a pointer to "junk" memory


11.3 Sample Code

Person *person =;

If we run in Xcode like the above code will be reported person.age = 20, this line of error, because the previous line has been relase, this is the memory address pointed to by the object is not available, also become a wild pointer.
Of course, if we send a message to the null pointer, there will be no error.

[email protected] and @synthesize

Let's write a piece of code first:

-(int) age; -(void) Setage: (int) age;

The above code is the simple access method of the setter and getter Method declaration of age, so is there a more convenient way to do it? The answer is @property and @synthesize.

There are several other keywords in @property, and they all have special effects, and I divide them into three categories: atomicity, accessor control, memory management.

12.1 atomicity
Atomic (default): Atomic means that the operation is atomic, meaning that only one thread accesses the instance variable. Atomic is thread-safe at least I am safe on the current device. It is a default, but rarely used. It is relatively slow, which is related to the arm platform and the internal locking mechanism.
Nonatomic:nonatomic and Atomic just the opposite. Represents a non-atomic and can be accessed by multiple threads. It's faster than atomic. However, there is no guarantee of security in a multithreaded environment, which is widely used in the case of single-threaded and explicitly only one thread access.


12.2 Accessor Control
ReadWrite (default): ReadWrite is the default, indicating both setter and getter.
Readonly:readonly says only getter has no setter.

12.3 Memory Management
Retain: Using retain means that the instance variable is taking ownership of the incoming parameter. It is shown in the setter that the instance variable is first release and then passed to it after the parameter is retain. The following code shows a similar behavior for retain:

-(void) Setstuname: (NSString *if (_stuname!= = [stuname retain];}}

Assign (default): Used for value types, such as int, float, double, and nsinteger,cgfloat, which represent pure replication. It also includes objects that do not have ownership relationships, such as common delegate.
Strong: The keyword introduced when arc was introduced with iOS is an optional alternative to retain. Indicates that the instance variable has a ownership relation to the passed-in parameter, which is a strong reference. Strong and retain have the same meaning and produce the same code, but the semantics better reflect the relationship of the object.
Weak:weak is similar to assign, unlike weak, which is automatically set to nil after the object is recycled. and weak smart is used in iOS 5 or later versions, for previous versions, using unsafe_unretained.
Unsafe_unretained:weak the lower version of the replacement.
Copy:copy is to keep a copy of itself for the instance variable.

Dark Horse programmer _ios Development _objective-c Learning Notes _ Class (object)

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.