[IOS learning basics] OC, ios basic oc

Source: Internet
Author: User

[IOS learning basics] OC, ios basic oc

A few days ago, it suddenly occurred to someone else's class. the m file contains the following code: @ synthesize xxxx = _ xxxx. At that time, the role did not understand what it meant. After that, it slowed down and found that the basic knowledge of some classes was forgotten, although you don't need to go into some of the old things in the past, you should review them.

I. Classes and objects

1. Class: A class is a blueprint or prototype that defines all attributes and methods of the same class.

2. Object: an object used to describe an objective object. It consists of specific attributes and methods.

3. Relationship between classes and objects: classes are engineering drawings used to create numerous objects.

4. Class features: Attributes

5. Class behavior: Method

Ii. Encapsulation

1. Classes are encapsulation, which encapsulates attributes and methods. It is an idea. Its core is to "expose necessary content to external users.(Private property Method)Users do not have to worry about internal details ".

We declare a Teacher class:

# Import <Foundation/Foundation. h> @ interface Teacher: NSObject {
// @ Public NSString * _ name; // member variable (instance variable) @ protected (protected) by default)

/* Note: @ protected, @ public, @ private, and @ package
* @ Public member variables can be accessed anywhere.
* @ Protected member variables can be accessed by declared classes and subclasses (default)
* @ Private member variables can only be accessed in the declared class (this is the member variable generated by @ Property by default)
* @ Package A @ package member variable is actually @ public in the executable file image implementing this class, but it is @ private outside.
*/} @ End

However, we cannot access this protected member variable at this time.

Method to access this member variable:

1> open the above "@ public" comment and access it by "->" outside

Teacher * tec = [[Teacher alloc] init]; tec-> _ name = @ "name ";

2> encapsulate the set and get methods for indirect access, add the method declaration in the. h file, and implement it in the. m file.

-(void)setName:(NSString *)name;-(NSString *)getName;-(void)setName:(NSString *)name{    _name = name;}-(NSString *)getName{    return _name;}

In this way, you can indirectly access the member variable by calling the method. In fact, the @ property keyword mentioned below helps you solve the access to the set and get methods.

Make it indirectly accessible in the form of "." (essentially by calling the set and get methods.

Teacher *tec = [[Teacher alloc] init];[tec setName:@"testName"];NSLog(@"%@",[tec getName]);

Summarize the member variables and member attributes:

① Member variables are instance variables

② Member attributes are used for indirect member variables in the category

③ If you want to make a feature of a class private and only access this class, it is defined as a member variable. If you want to access a feature of this class outside the class, you can define it as a member attribute.

III, @ Property and @ synthesize keywords

  1. In the past, we often saw declarations of this type.

# Import <Foundation/Foundation. h> @ interface Teacher: NSObject {NSString * _ name; // member variable} @ property (nonatomic, copy) NSString * name; // member attribute @ end # import "Teacher. h "@ implementation Teacher @ synthesize name = _ name; @ end

 This is in the previous compiler features:

@ Property: Declares the set and get methods of the name attribute.

@ Synthesize name = _ name indicates that the set and get methods are implemented for the attribute name declared by @ property. "= _ name" indicates that the member Variable _ name is accessed during implementation.

2. Currently, we only need one sentence to declare an attribute for the class (I usually use this method for convenience ):

@ Property (nonatomic, copy) NSString * name; // it is declared in the. h file.

This is in the new compiler features:

@ Property directly helps us do three things:

① When the member variable of the name attribute is not specified, a member variable with the default value of _ name will be generated, but the property is @ private (private ), write @ protected (protected)

② Set and get methods for declaring the name attribute

③ Set and get methods for implementing the name attribute

Note: If you want to use a self-generated member variable, use the previous format in. add a member variable in. add @ synasize xxx = _ xxx to the m file.

Benefits of naming member variables with underscores:

① Differentiate member variables and attributes

② Prevent naming conflicts between local variables and member variables

4. Several statements about inheritance

1. Inheritance: establishes the relationship between classes, achieves code reusability, and facilitates system expansion.

2. inheritance is a feature that extends to avoid repeated definitions of the same member variables in multiple similar classes.

3. Inheritance has a single nature and transmission

4. The inherited class is called a parent class or a base class, And the inherited class is called a subclass or a derived class.

5. super Keyword: self is used to access the class members, while super is used to access the parent class members in the subclass.

V. Category catagory

Classification: ① add some methods for the class without changing the original class to expand the class.

② During development, we generally add categories for the classes provided by the system. In addition, you can write your own class modules and methods that implement different functions in different categories. A class can have unlimited classes.

1. Classification is also called informal Protocol: A category (catagory) of the NSObject class and its sub-classes ).

# Import "Teacher. h "@ interface Teacher (Log) + (void) log; @ end # import" Teacher + Log. h "@ implementation Teacher (Log) + (void) log
{
NSLog (@ "category ");
} @ End

As shown in the preceding classification, we have added a classification "Teacher + Log. h" for the Teacher class. The class method + (void) log is declared and implemented in the classification;

2. Class Extension: anonymous classification.

In the Teacher. m file

# Import "Teacher. h "@ interface Teacher () // This method is anonymous classification @ property (nonatomic, copy) NSString * nickName; // attributes can be added to an anonymous classification, however, this attribute defaults to @ private and can only use + (void) log in this class; // declares a class method log @ end @ implementation Teacher @ synthesize name = _ name; // implement this method + (void) log {NSLog (@ "anonymous Classification");} @ end

Then we call the log method and print the following

It is proved that classification (informal Protocol) will rewrite this class and its class extension (anonymous classification) method.

3. in catagory, anonymous classes allow adding attributes and automatically generate member variables, set, and get methods. However, in informal protocols, @ property can be used to declare an attribute, it does not provide you with the set, get method, and member variables. If you use them directly, it will cause a crash. As follows:

1> I added an attribute nickName to the header file of Teacher + MyProperty. h;

#import "Teacher.h"@interface Teacher (MyProperty)@property (nonatomic,copy)NSString *nickName;@end

2> Use (crash due to lack of set and get methods)

Teacher * tec = [[Teacher alloc] init]; tec. nickName = @ "nickNmae"; NSLog (@ "% @", tec. nickName); // print 16:58:13. 656 category [2002: 159549]-[Teacher setNickName:]: unrecognized selector sent to instance 0x10020.e102016-01-24 16:58:13. 658 category [2002: 159549] **** Terminating app due to uncaught exception 'nsinvalidargumentexception ', reason:'-[Teacher setNickName:]: unrecognized selector sent to instance 0 X1001_e10' *** First throw call stack :......

3> how to add attributes in informal protocols (Classification) [oc provides a solution for this phenomenon: Associated Object. write the following code in the m file:

#import "Teacher+MyProperty.h"#import <objc/runtime.h>static void *strKey = &strKey;@implementation Teacher (MyProperty)-(void)setNickName:(NSString *)nickName{    objc_setAssociatedObject(self, &strKey, nickName, OBJC_ASSOCIATION_COPY);}-(NSString *)nickName{     return objc_getAssociatedObject(self, &strKey);}@end
Vi. protocol

1. there are informal protocols, and there are also formal protocols. protocol is used to declare a lot of methods, waiting for implementation, as long as a class complies with a certain protocol, then this class has all the method declarations of the Protocol. (Note: Only the. h declaration file exists in the Protocol.) The format is as follows:

@ Protocol Teach <NSObject>
@ Required;-(void) teach :( NSString *) text; // declares a teach method, which is required by default @ optional; @ end // a new name named Teach is created. protocol header file of h

2. The class can comply with the Protocol (Teacher complies with the teach Protocol)

    

3. Implementation Method

-(Void) teach :( NSString *) text {NSLog (@ "");}

4. A class can only inherit from one parent class (the root inheritance), but one class can comply with multiple protocols.

VII. Associated Object-Extension

1. The correlated object is similar to a member variable, but it is added at runtime. (This is used to solve the problem of adding attributes to a category. The reason has been described above. I will not describe it here)

2. We can think of an associated object as an OC object, which is connected to an instance variable of a class through a key.

3. Because the C interface is used, the key is a void pointer (const void *). We also need to specify a memory management policy to tell Runtime how to manage the memory of this object. The options of the memory management policy are as follows:

// When the host object is released, the associated object is processed according to the specified memory management policy. When we need to process multi-threaded code that accesses the associated object in multiple threads, this is very useful for typedef OBJC_ENUM (uintptr_t, objc_AssociationPolicy) {OBJC_ASSOCIATION_ASSIGN = 0, priority = 1, OBJC_ASSOCIATION_COPY_NONATOMIC = 3, OBJC_ASSOCIATION_RETAIN = 01401, OBJC_ASSOCIATION_COPY = 01403};/* If the specified policy is assign, the correlated object will not be released when the host is released; if retain or copy is specified, the associated object will be released when the host is released. We can even choose whether it is automatic retain/copy. */

4. Use

1> void objc_setAssociatedObject (id object, const void * key, id value, objc_AssociationPolicy policy) method: connect an object to other objects

Parameter 1: source object, which is generally self.

Parameter 2: key, used to indicate the key of an attribute. More than one attribute may be added to the category.

There are three common methods:

static void *strKey = &strKey;

    ② static NSString *strKey = @"strKey";

    ③ static char strKey;

Parameter 3: associated object

Parameter 4: association policy

The self object will get a new associated object anObject, and the memory management policy is to automatically retain associated objects. When the self object is released, it will automatically release associated objects. In addition, if we use the same key to associate another object, the previously associated object will be automatically released. In this case, the previously associated object will be properly processed, and the new object will use its memory.

2> id anObject = objc_getAssociatedObject (self, & myKey) method to obtain the associated object

3> the objc_removeAssociatedObjects (self) method removes all associations.

5. Application (UIAlertView + Block classification, click the event button as the delegate monitoring option, and use the block as the associated object)

# Import <UIKit/UIKit. h> typedef void (^ CompleteBlock) (NSInteger buttonIndex); @ interface UIAlertView (Block) // callback using Block. In this case, self is used as the Delegate-(void) by default) showAlertViewWithCompleteBlock :( CompleteBlock) block; @ end # import "UIAlertView + Block. h "# import <objc/runtime. h> @ implementation UIAlertView (Block) static char key; // callback using the Block method. At this time, self is used as the Delegate-(void) showAlertViewWithCompleteBlock :( CompleteBlock) by default) Block {if (block) {// remove all associated objc_removeAssociatedObjects (self);/** 1 create an association (source object, keyword, associated object, and an association policy .) 2. the keyword is a void pointer. Each associated keyword must be unique. Static variables are usually used as keywords. 3. The association policy indicates whether the related objects are associated by assigning values, retaining the reference or copying methods, and whether the association is atomic or non-atomic. The association policy here is similar to the attribute declaration. */Objc_setAssociatedObject (self, & key, block, OBJC_ASSOCIATION_COPY); // set delegate self. delegate = self;} [self show];}-(void) alertView :( UIAlertView *) alertView clickedButtonAtIndex :( NSInteger) buttonIndex {// get the associated object with the keyword. CompleteBlock block = objc_getAssociatedObject (self, & key); if (block) {// block Value block (buttonIndex );}} /** the association in OC is to add object parameters based on existing classes. To expand the original class, you need to introduce the # import <objc/runtime. h> header file. The Association is based on a key to distinguish different associations. Common functions:
Objc_setAssociatedObject sets the association objc_getAssociatedObject to obtain the association objc_removeAssociatedObjects to remove the Association * // Of course, it does not have to be so troublesome. inheritance can also be easily implemented. @ End
VIII. loading classes (two methods)
/*** These two methods are called at the beginning of the program running. * We can use them to do some preprocessing before the class is used. * For example, the class automatically saves its class name to an NSDictionary. * // while initialize is called before the first method of the class or its subclass is called. + (Void) initialize; // The load method is called as long as the file of the class is referenced. + (void) load;/*** so if the class is not referenced in the project, there will be no load calls. * However, even if the class file is referenced, it is not used, so initialize will not be called */
IX. Reflection

1. reflection: in short, the class object is returned through the class name (using the import before # import <objc/runtime. h> the header file. The associated object in front of the file also uses this header file. It seems that there are a lot of things to learn about this runtime. I have reviewed and found a lot of new things to learn ,-_-, let's take a look at the basics)

// Class name returned Class Object + (NSObject *) createBean :( NSString *) className {Class tempClass = NSClassFromString (className); NSObject * obj; if (tempClass) {obj = [[tempClass alloc] init];} return obj ;}

2. Get the property name set by Class Name

+ (NSArray *) propertyOfClass :( NSString *) className {NSMutableArray * arr = [NSMutableArray arrayWithCapacity: 0]; // obtain the const char * cClassName = [className UTF8String]; id theClass = objc_getClass (cClassName); unsigned int outCount, I; objc_property_t * properties = class_copyPropertyList (theClass, & outCount); for (I = 0; I <outCount; I ++) {objc_property_t property = properties [I]; NSString * propertyNameString = [[NSString alloc] initWithCString: property_getName (property) encoding: NSUTF8StringEncoding]; [arr addObject: propertyNameString];} return arr ;}

3. Through reflection (combined with KVC), we can convert json strings to objects through class names, data sources, and conventions.

4. The third-party library learns the NSObject + MJClass conversion model in MJExtension.

 

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.