Learn the understanding of ios--code blocks (block) and error exception handling

Source: Internet
Author: User

1, Object C code block (block)

OBJECTIVE-C code block from just learning time, feel a little strange, slowly feel it in C # is also a bit familiar with, it is introduced in the objective-c, it seems to be mainly used to solve the code callback and synchronous call problems, here, if familiar with C # features, Probably think of the action<t> and func<t> Concepts in C #, yes, they are feather, haha.

Code blocks are essentially similar to other variables. The difference is that the code block stores the data as a function body. With code blocks, you can pass in the number of arguments as you would call other standard functions, and get the return value, the character (^) is the syntax tag for the code block.

As the following example is the definition of a code block

void (^simpleblock) (void) = ^{        NSLog (@ "This isa block");    

Once you've defined it, you can use it like a function, and see if the code below looks familiar to you.

Simpleblock ();

Of course, for such things, it can also accept parameters, even if the parameters are not a problem, if it is a parameter, it should be similar to C # func<t>, here is a two-parameter code block example.

Double (^multiplytwovalues) (double double) =                              ^ (double double secondvalue) {                                  return Firstvalue * secondvalue;                              };     double result = Multiplytwovalues (2,4);

Such a block of code, it can also get the local variables defined inside the class, but because of its particularity, it seems that if it does not add special processing, it gets to the variable or the value of the property, is the snapshot of the moment it appears.

The following example is a good introduction to the fact that the content in the code block is snapshot.

int ;     void (^testblock) (void) = ^{        NSLog (@ "Integer is:%i", Aninteger);     ;     Testblock ();

The above code block, the printed value, is 42, not 84, because it appears in the code block at the moment, the local variable, and then did not follow the change of the Mass.

Is there a workaround for this approach that allows it to change automatically depending on the variable? Of course, there is a need for special treatment, the answer is to use __block to identify, it can follow the pace of the large forces.

If the definition of the variable in the above code block uses this keyword, then the value appears to be 84, as shown in the following code block.

int ;     void (^testblock) (void) = ^{        NSLog (@ "Integer is:%i", Aninteger);     ;     Testblock ();

This __block feature is powerful, telling the compiler that it can get the latest value of a variable, or that it can be modified in a code block (dangerous?). Anyway, you know it.

As I said earlier, the code block inside the OBJECTIVE-C is similar to the lambda action and Func in C #, so let's give an example of the next.

Compare the following two sets of code, one is the OBJECTIVE-C code block

void (^methodblock) (int); -(void) Foowithblock: (methodblock) block{    int5;    Block (a);} -(void) regularfoo{    [self foowithblock:^ (int val)     {        NSLog (@ "  %d", Val);    }];}

Then there's a code example in C # that feels like they're close. Here, you may sigh, the programming language of the world, very small, the world is tending to Datong.

void Foo (action<int> m) {    int5;    M (a);} void Regularfoo () {    //  Or:foo (delegate (int val)    {        Console.WriteLine (val);    });}

However, the use of code blocks, you will slowly feel that although it is very powerful, but many places are not very easy to understand, after all, for those of us who are not very deep foundation of the people, to slowly digest.

Take a look at the following example code, the code block definition inside this method, very interesting.

-(void) Begintaskwithcallbackblock: (void (^) (void)) Callbackblock {    ...    Callbackblock ();}

Take a look at the following code block, you may be more dizzy, nothing, dizzy on the right, indicating that you are a normal person.

void (^ (^complexblock) ( Void (^) (void))) (void) = ^ (void (^ablock) (void)) {    ...    return ^{...        };    

Finally remember, if a method has more than one parameter, remember to put the code block parameters at the end of the definition.

-(void) Begintaskwithname: (NSString *) name completion: (void(^) (void)) callback;

As for how the code block simplifies the synchronous call problem, let the reader to understand the research, I feel a little dizzy. Ha ha.

2. Error and exception handling of Object C

We know that when developing various applications or systems, it is difficult to avoid errors, and effective handling of error anomalies is a very necessary content for you. In C #, if we need to throw an exception, we use the throw method, and all errors are extended with the exception object Exception as the base class, including a variety of exception objects, while the catch of the error exception is through try {} catch (Exception ex) Finally {} This kind of code or similar processing, for objective-c, it is how to handle the error exception?

In fact, the objective-c is similar to the mechanism of error handling, and its support for exceptions includes four compiler directives: @try , and @catch @throw @finally。是不是又一次感觉到语言的大同了,这个东西和C#的处理几乎没有什么差别。

In addition, OBJECTIVE-C also introduced a nserror thing, what does this thing have to do with nsexception? This thing is a bit like when we developed in C #, add an out input parameter, used to pass the error message inside the program, and then hand over to the caller, so that they love how to use it, anyway, I finished the processing, there is no error I told you. As the nserror can be transmitted more abundant information, in general, the processing of the program is also very convenient.

If the network connection is abnormal, you can pass it through the following code.

-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error;

Let's take a look at a file error how to deal with, first define a function, including the parameters of the Nserror, note that the general parameter is put to the last, this seems to be the same as we have some of the C # Convention to deal with the same.

-(BOOL) Writetourl: (Nsurl *) Aurl           options: (nsdatawritingoptions) Mask             error: (Nserror *) errorptr;

When we call this writetourl function, there is an error that should be handled, when the error occurs, it executes, and returns the value of No

    Nserror *anyerror;    BOOL success = [Receiveddata writetourl:somelocalfileurl                                    options:0                                      error:&anyerror];    if (!success) {        NSLog (@ "Write failed with error:%@", anyerror);        // present error to user    }

To indicate the source of the error, Nserror has a domain attribute, which is typically distinguished by the company's name (or special name).

Com.iqidi.appOrFrameworkName.ErrorDomain

The code for constructing a nserror is probably as follows.

@" Com.iqidi.MyApplication.ErrorDomain "; NSString *desc = nslocalizedstring (@ "unable to ... " @""); Nsdictionary *userinfo = @{Nslocalizeddescriptionkey:desc}; Nserror *error = [nserror errorwithdomain:domain                                         code:-101 userinfo:userinfo                                     ];

And the general anomaly, we generally still through the nsexception processing, the exception is the time when the problem occurs, stop to ask how to deal with the first time, if there are processing lines in accordance with the treatment of the line, otherwise on the level of the push up.

Its processing is similar to C #, and we are familiar with the code structure as shown below.

@try {    //  code that throws-an exception ...    } @catch // Most specific type     // handle exception CE    ...} @catch // Less specific type     // Do whatever recovery are necessary    at he level ...    // Rethrow the exception so it's handled at a higher    level @throw;} @catch (ID//  least specific type    //  code that handles this exception     ...} @finally {    //  perform tasks necessary whether exception occurred ornot    ...}

Exception construction and throw code are similar to C #

nsexception* myexception = [nsexception        exceptionwithname:@ "filenotfoundexception"        reason:@ "File not Found on System"        Userinfo:nil]; @throw myexception;

If you need to handle the memory release of some objects while handling exceptions, it is common to put it in the code block contained in the @finally.

This is similar to C #, although C # does not need to deal with memory release issues, but for some time-consuming operands, such as connection, it is generally best to put the finally inside to make sure that it is closed and handled similarly.

-(void) dosomething {    Nsmutablearray *anarray = nil;    Array = [[Nsmutablearray alloc] initwithcapacity:0];    @try {        [self dosomethingelse:anarray];    }    @finally {        [Anarray release];    }}

If you want to throw an original exception, this is similar to C #, by @throw;

@try {    NSException *e = [nsexception        exceptionwithname:@ 'filenotfoundexception'         Reason:@ "File not Found on System"        Userinfo:nil];    @throw e;} @catch (NSException *e) {    @throw//  rethrows e implicitly}
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.