From C ++ to objective-C: Exception Handling and Multithreading

Source: Internet
Author: User


Http://www.devbean.info/2011/04/from_cpp_to_objc_17/


Exception Handling


Compared with C ++, exception handling in objective-C is more like Java, mainly because objective-C has a @ finally keyword. A similar finally keyword exists in Java, but not in C ++. Finally is try ()... An optional additional block of the catch () block.CodeIt must be executed, whether or not exceptions are caught. This design can easily write brief and clean code, such as releasing resources. In addition, @ try… in objective-C... @ Catch... @ Finally is a classic design with no difference from most languages. However, unlike C ++, objective-C can only be discarded by objects.


Without finally With finally
BOOL problem = YES;
@try {
     dangerousAction ();
     problem = NO;
} @catch (MyException * e) {
     doSomething ();
     cleanup ();
} @catch (NSException * e) {
     doSomethingElse ();
     cleanup ();
     // rethrow exception
     @throw
}
if (! problem)
     cleanup ();
@try {
     dangerousAction ();
} @catch (MyException * e) {
     doSomething ();
} @catch (NSException * e) {
     doSomethingElse ();
     @throw // rethrow exception
} @finally {
     cleanup ();
} 


Strictly speaking, @ finally is not necessary, but it is indeed a powerful tool to handle exceptions. As shown in the previous example, we can also throw an exception in @ catch. In fact, @ finally is executed only after @ try is completed. We will explain this below.


int f (void)
{
     printf ("f: 1-you see me \ n");
     // Pay attention to the output string and experience the exception handling process
     @throw [NSException exceptionWithName: @ "panic"
                                    reason: @ "you do n’t really want to known"
                                  userInfo: nil];
     printf ("f: 2-you never see me \ n");
}
 
int g (void)
{
     printf ("g: 1-you see me \ n");
     @try {
         f ();
         printf ("g: 2-you do not see me (in this example) \ n");
     } @catch (NSException * e) {
         printf ("g: 3-you see me \ n");
         @throw;
         printf ("g: 4-you never see me \ n");
     } @finally {
         printf ("g: 5-you see me \ n");
     }
     printf ("g: 6-you do not see me (in this example) \ n");
} 


Finally, catch (…) of C ++ (...) Any value can be captured, but not in objective-C. In fact, only objects can be thrown, that is, we can always use ID to capture exceptions.



Note that there is an nsexception class in cocoa. We recommend that you use this class as the parent class for all Exception classes. Therefore, catch (nsexception * E) is equivalent to catch (…) of C ++ (...).


Multithreading


Thread Security



In objective-C, POSIX APIs 2 can be clearly used to implement multithreading. Cocoa provides its own multi-thread class management. One thing to note is that when multiple threads access the same memory area at the same time, unexpected results may occur. Both POSIX APIs and cocoa provide lock and mutex objects. Objective-C provides a keyword @ synchronized, which is the same as the keyword of the same name in Java.



@ Synchronized



By @ synchronized (...) The surrounding block is automatically locked to ensure that only one thread is used at a time. This is not the best solution for processing concurrency, but it is the simplest, most lightweight, and most convenient solution for most key blocks. @ Synchonized requires that an object be used as a parameter (can be any object, such as Self) and used as a lock.


  @ implementation @implementation MyClass
 
-(void) criticalMethod: (id) anObject {
     @synchronized (self) {
         // This code is mutually exclusive to other @synchronized (self)
         // self is the same object
     }
     @synchronized (anObject) {
         // This code is mutually exclusive to other @synchronized (anObject)
         // anObject is the same object
     }
}
@end 
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.