Object C Grammar Learning Note (i)

Source: Internet
Author: User

1.@property paired with @synthesize.

The purpose of @property precompiled directives is to automatically declare the setter and getter methods of the property.

@synthesize Create an access code for this property

function: Let the compiler automatically write a method declaration with the same name as the data member, omitting the declaration of the read-write method.

2. strong references (__strong) and weak references (__weak)

in the arc mode of OBJECTIVE-C,

ID obj1 = [[NSObject alloc] init];

Although there are no declarations shown as __strong, an object declared by default by Objective-c is __strong, which is:

ID obj1 = [[NSObject alloc] init];

And

ID __strong obj1 = [[NSObject alloc] init];

is equivalent.

In a strong reference, sometimes a circular reference occurs, and a weak reference is required to help (__weak).

A strong reference holds an object, and a weak reference does not hold an object.

A strong reference can free an object, but a weak reference cannot, because a weak reference does not hold an object, and when a weak reference points to an object held by a strong reference, the weak reference is automatically assigned nil when the strong reference is freed, i.e. the weak reference automatically points to nil.

The following code is used to illustrate:

  strong references and weak references in main.m//arc//#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { c2/> @autoreleasepool {        id __weak obj0 = nil;        if (YES) {            id obj1 = [[NSObject alloc] init];            Obj0 = obj1;            NSLog (@ "obj0:%@", obj0);        }        NSLog (@ "obj0:%@", obj0);    }    return 0;} /* *  Output results *  obj0: <NSObject:0x1003066c0> *  obj0: (NULL) * * Because the  obj1 generated default is a strong reference (__strong), After the scope of the if is exceeded, the object held by Obj1 is freed, *  Obj0 is a weak reference, so obj0 does not hold the object, after the Obj1 object is released, Obj0 automatically assigned to nil *  Weak reference attribute is, do not hold the object, even if it is written as ID __ Weak obj1 = [[NSObject alloc] init]; *  This code system will give a warning, because here obj1 is declared as a weak reference, then after the assignment, alloc out of the object will be released immediately. */

3. Point Expressions , which can be used to access objects, similar to the C language of struct-body access.

The point expression appears to the left of the equals sign, the setter method of the variable name is called, and the point expression appears to the right of the equal sign, and the getter method of the variable name is called.

4. What is category

The category pattern is used to add methods to existing classes to extend existing classes, and in many cases the category is a better choice than creating subclasses. The newly added method will also be automatically inherited by all subclasses of the extended class. When you know that a method in an existing class has a bug, but the class is in the form of a library, and we cannot modify the source code directly, the category can also be used to replace the entity of a method in the existing class to fix the bug. However, there is no convenient way to call the existing class of the original is replaced by the method entity. It is important to note that when you are ready to have a category to replace a method, be sure to implement all the functions of the original method, otherwise this substitution is meaningless and will cause new bugs. Unlike subclasses, category cannot be used to add instance variables to an extended class. Category is often used as a tool for organizing framework code.

Use of category

1. Implement an extension of an existing class without creating an inherited class.

2. Simplify the development of the class (When a class requires multiple programmers to co-develop, the category can put the same class in different source files according to the purpose, thus facilitating the programmer to independently develop the appropriate collection of methods).

3. Group the commonly used related methods.

4. In the absence of source code can be used to fix the bug.

Usage of category

In Obj-c, the way to declare a category extension for an existing class is as follows:

@interface ClassName (CategoryName)  -methodname1  -methodname2  @end  

The above declarations are usually in. h files, and then we implement these methods in the. m file:

@implementation ClassName (CategoryName)  -methodname1  -methodname2  

We created an iOS single View applciation named Categoryexample. Then create a category extension for the NSString class. File->new->file then select Cocoa Touch objective-c category. Named Reversensstring. The system automatically generates a fixed format classname+ CategoryName. h and. m files.

Declaring category

Open the Nsstring+reversensstring.h file and add the following code inside:

#import <Foundation/Foundation.h>  @interface nsstring (reversensstring)  + (nsstring*) ReverseString: ( nsstring*) strsrc;  @end  

Implementing category

The ReverseString method is implemented in the NSSTRING+REVERSENSSTRING.M file:

#import "Nsstring+reversensstring.h"  @implementationNSString (reversensstring)  + (nsstring*) reversestring :(nsstring*) strsrc;  {      nsmutablestring *reversedstring =[[nsmutablestring alloc]init];      Nsinteger CharIndex = [strsrc length];      while (CharIndex > 0) {          charindex--;          Nsrange Substrrange =nsmakerange (CharIndex, 1);          [Reversedstring Appendstring:[strsrcsubstringwithrange:substrrange];      }      return reversedstring;  }  @end  

The rest of the work is to verify our category, add a button reversestring to the view, and set the corresponding action method to reversestring. Add a label to the view, named MyString, and the default value is "Hellocategory Design pattern!". Click the button to reverse the string. The main code is as follows:

-(Ibaction) ReverseString: (ID) Sender {      NSString *test = [Nsstringreversestring:_mystring.text];      _mystring.text = test;     }  

Code Organization

Category is used for large class efficient decomposition. Usually a large class method can be decomposed into different groups according to some logic or correlation, the larger the code size of a class, the more useful it is to decompose the class into different files, each of which is a collection of some related methods of the class.

When multiple developers work together on a project, each individual is responsible for the development and maintenance of a separate cagegory. This makes versioning easier because there is less work conflict between developers.

Category vs Add sub-class

There is no well-defined criterion to be used as a guideline for when to use categories to add subclasses. However, there are several guiding suggestions:

      1. If you need to add a new variable, you need to add a subclass.
      2. If you just add a new method, using category is the better choice.

5.Class Extension (class extension)

Class extensions is used to solve two problems:

    1. Allows an object to have a private interface and can be validated by the compiler.
    2. Supports a public read-only, private writable property.

To define a private function, you typically declare a "private" category in the implementation file:

@interface MyClass (Private)
-(ID) Awesomeprivatemethod;
@end

However, the private method of a class is often expected to be implemented in the @implementation block of the class, rather than in a separate @implementation block, as in the above category method. In fact, the category merely compensates for the objective-c lack of public/private limits.

The real problem is that the Objective-c compiler will assume that the methods declared in the category will be implemented elsewhere, so the compiler will not try to verify that they are actually implemented. In other words, the method that the developer declares may not be implemented, and the compiler will not have any warning. The compilation will assume that they will be implemented elsewhere or in separate files.

With class exteionsion, the implementation of the methods and properties declared in it will be placed in the @implementation chunk of class. Otherwise, the compiler will make an error.

SOMECLASS.M @interface SomeClass ()-(void) extend;  @end  @implementation SomeClass//All declarations in the header file or in the parent class of the implementation of the method//or some private function-(void) Extend {     //implement private method here; }  @end

Public readable, privately writable attributes (Publicly-readable, privately-writeable properties)

A common benefit of implementing an immutable (immutable) data structure is that external code cannot modify the state of an object with a setter. However, you might want it to be a writable property inside. Class extensions can do this: in a public interface (the declaration of a Class), the developer can declare that a property is read-only and is then declared writable in the class extension. In this way, the property will be read-only for external code, but the internal code can use its setter method.

@interface Myclass:nsobject  @property (retain, readonly) float value;  @end     //private extension, hidden in the master implementation file.  @interface MyClass ()  @property (retain, readwrite) float value;  @end  

6. determine the type of object

The ability of an object to acquire its type at run time is called introspection. Introspection can be accomplished in a number of ways.

-(BOOL) Iskindofclass:classobj to determine if this class or subclass of this class is an instance of

-(BOOL) ismemberofclass:classobj to determine if it is an instance of this class

Object C Grammar Learning Note (i)

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.