Objc uses block to implement chained programming and objcblock chained Programming

Source: Internet
Author: User

Objc uses block to implement chained programming and objcblock chained Programming

Objc uses block to implement chained Programming

  

  Because it is hard to read. Like Anonymous functions in other languages, block is difficult for many programmers to take the initiative to use it at the beginning.

This article describes the actual use of block as an attribute, understands block, and explains how to use block to implement chained programming.

[1] experiences

Today, the most commonly used language in iOS development is objc. The market is like the Titanic. Although people are upstairs, the ship is sinking, so people are still sinking. Despite swift's rapid appearance, most developers still face objc. When does swift replace objc? Today's objc developers don't have to worry too much about it. Maybe the boat will sink (Apple bless ).

The biggest headache for objc is his expression that looks like a tribal language. For example, the following line of newbie code is as obscure as the parity signal:

 [[NSMutableDictionary alloc] initWithContentsOfURL:[NSURL URLWithString:@"a.txt"]][@"persons"][12];

However, it does not tell anyone anything meaningful. The syntax is as follows:

NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithContentsOfURL:[NSURL URLWithString:@"a.txt"]];NSArray* arr = dict[@"persons"];arr[12];

Today, the universal value of code is not efficiency, but development efficiency. This is why java becomes the king. Because java writes fast and reads well.

[2] Exploration

Objc is slow and hard to read than java. So how can we make objc look like java. Looking at all the syntax of objc, only block can be used. Let's look at the definition of block.

ReturnType (^ name) (val1, val2 ,...); return type variable name parameter list // we can think of it as a pointer to the function from the surface. This function looks like this (returnType) name (val1, val2 ,...) {//......}

Block has the appearance of a function and is treated as a variable. Block has two functions. First, it can be 'point' as a class property. Second, it can be called directly as a function. The following explains one by one. The attributes of the first class can be clicked, for example, person. name; which is very understandable. You must have seen it, str. length; right. Second, block is used as a variable, but it can be called as a pointer to a function.

NSString * (^ myBlock) () = ^ () {return @ "le" ;}; // defines a return value of the NSString type, without any parameters, and its name is myBlock blockmyBlock (); // This line calls NSString result = myBlock (); // This is the return value obtained after the block is retrieved, that is, @ "Jule"

Here I will explain the definition of block again: The above myBlock can be considered as a pointer to a function defined below. This function is

(NSString *) myBlock (){//...} // The pointer to the function NSString * (* p) (); // you can think that the pointer p is myBlock (in fact, the real identity of the block is more complex)

[3] reasoning

Let's assume that objc is written like this.

// Set the view position and size, and set the view background color view. setFrame (0, 0, 50, 50 ). setBackgroundColor (@ "# 0c0c0c ". toColor (); // remove spaces and print the word verse on the console @ "the day goes to the mountains, and the Yellow River enters the sea flow ". removeStr (@""). nslog ();

In fact, five lines of code are required. One line is 3 seconds, and three lines are 15 seconds. In this way, we missed a chance to shake a shake, and our life was slow and difficult, but we knew nothing about it.

View. frame = CGRectMake (0, 0, 50, 50); view. backgroundColor = [UIColor colorWithRed: 0.5 green: 0.5 blue: 0.5 alpha: 1.0]; NSString * str = @ "when the day ends, the Yellow River enters the sea "; str = [str stringByReplacingCharactersInRange: @ "" withString: @ ""]; NSLog (str );

Now let's analyze how to use block to implement chained programming. Let's look at this sentence:

view.setFrame(0,0,50,50).setBackgroundColor( @"#0c0c0c".toColor() );

Where are setFrame and setBackgroundColor? You must know that it is a property. However, attributes are not enclosed in parentheses. Is setFrame () an attribute? So what is it? SetFrame () is an attribute and belongs to the block type, because the block can be called in parentheses. Just like calling block () in this way, there is another problem that is critical: view. setFrame (). setBackgroundColor (); how can we continuously click out? This is hard to understand at the beginning. This is not difficult. Let's look at the sentence:

NSString result = myBlock();

We carefully discovered that the block can return values, so we can click a bunch of attributes based on the returned values, so that our chain programming idea will pass.

Iv. Practice

Now let's implement view. setFrame (). setBackgroundColor ();

First, prepare a category. The header file is defined as follows:

//  UIView+Extension.h#import <UIKit/UIKit.h>@interface UIView(Extesion)@property (nonatomic,copy) UIView* (^setFrame)(CGFloat x, CGFloat y, CGFloat w, CGFloat h);@property (nonatomic,copy) UIView* (^setBackgroundColor)(UIColor* color);@end

We have extended two additional attributes setFrame and setBackgroundColor in the UIView class, which means that as long as they are objects inherited from the UIView, they can be clicked out.

Now we need to understand the two differences:

View. setFrame; // This is the get attribute, which returns a blockview. setFrame (); // This is the get attribute. It returns a block and uses parentheses to call this block. The returned value of this block is an object of the UIView type, then he can continue to click the next attribute.

View. setFrame () executes the block because of the parentheses added at the end of the sentence, and its return type is a UIView object, so you can call setBackgroundColor ();

Here, I will explain why the copy and block types are originally value types. They are originally on the stack. If any strong pointer passes through the ARC environment, the compiler will copy the file to the heap memory. The retain action of a block is implemented by the copy action by default. Because the block variable is declared as a stack variable by default, copy should be used outside the block declaration.

The following code is implemented in the. m file:

- (UIView *(^)(CGFloat, CGFloat, CGFloat, CGFloat))setFrame{    return ?;}

It is not difficult to find out that the type of this attribute is block, specifically the UIView * (^) (CGFloat, CGFloat) type. Then '? 'Is such a type object. But where can this object be obtained? If it is an NSString, I still store it, and this object can only be obtained. This is not important, because we do not need to block the object itself. What we need is that the block object can execute some functions. Therefore, a temporary block object is returned within the attribute. Some functions are executed inside the block. The most important thing is that the UIView object must be returned inside the block. The compiler strictly checks the block type.

-(UIView * (^) (CGFloat, CGFloat) setFrame {return ^ (CGFloat x, CGFloat y, CGFloat w, CGFloat h) {// return block self of the temporary variable. frame = CGRectMake (x, y, w, h); // return self; // return value after the block is executed };}

Below is the implementation of the. m file

// UIView + Extension. m # import "UIView + Extension. h "@ implementation UIView (Extesion)-(UIView * (^) (CGFloat, CGFloat) setFrame {return ^ (CGFloat x, CGFloat y, CGFloat w, CGFloat h) {self. frame = CGRectMake (x, y, w, h); return self ;};}- (void) setSetFrame :( UIView * (^) (CGFloat, CGFloat )) setFrame {}; // This attribute does not need to be set from outside. If you do not want to report a warning, write the empty method-(UIView * (^) (UIColor *)) setBackgroundColor {return ^ (UIColor * color) {self. backgroundColor = color; return self ;};}-(void) setSetBackgroundColor :( UIView * (^) (UIColor *) setBackgroundColor {}; @ end

[5] Crash

In objc, sending any messages to the nil object will not crash, but the type of messages that cannot be processed will crash, which is also the most common situation. In addition, this will crash: nil. length; view. length; properties that do not exist in the call will also crash. This is an important situation for us to handle.

Imagine that a single line of code suddenly returns nil to the next link, and the call will crash. The key is that the breakpoint does not clearly tell you which line it is in. We can only obtain debugging information from the console. This is also one of the drawbacks of chain programming.

In order to deal with this situation, I wrote a chain programming framework LinkBlock for unified processing and chained encapsulation for almost all common functions. There is no threshold. I hope you can help me find a star, supports tianchao as a good programmer.

[Hope you can help me find a star]

[6] efficiency

Efficiency must be lower than native because an attribute call is added, a temporary block is created, and a block is executed. The goal of bloggers is to improve development efficiency and reduce some operational efficiency. Sometimes it is worthwhile.

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.