NSHipster Obscure Topics in Cocoa and Objective C

@

Instance Variable Visibility

  1. @public: instance variable can be read and written to directly, using the notation person->age = 32"

  2. @package: instance variable is public, except outside of the framework in which it is specified (64-bit architectures only)

  3. @protected: instance variable is only accessible to its class and derived classes

  4. @private: instance variable is only accessible to its class

Exception Handling

(前面加@符号和其它语言进行区分)

@try
{
  // attempt to execute the following statements
    ![self getValue:&value error:&error];
  // if an exception is raised, or explicitly thrown...
  if (error)
  {
    @throw exception;
  }
}
@catch(NSException *e)
{
    // ...handle the exception here
}
@finally
{
  // always execute this at the end of either the @try
or @catch block
    [self cleanup];
}

Objective-C Literals

  1. @selector(): Returns an SEL pointer to a selector with the specified name. Used in methods like -performSelector:withObject:.

  2. @protocol(): Returns a Protocol pointer to the protocol with the specified name. Used in methods like *-conformsToProtocol:.

C Literals

  1. @encode(): Returns the type encoding of a type. This type value can be used as the first argument encode in NSCoder -encodeValueOfObjCType:at.

  2. @defs(): Returns the layout of an Objective-C class. For example, to declare a struct with the same fields as an NSObject, you would simply do:

     struct
     {
       @defs(NSObject)
     }
    

    @defs is unavailable in the modern Objective-C runtime.

Optimizations

  1. @autoreleasepool{}: If your code contains a tight loop that creates lots of temporary objects, you can use the @autorelease directive to optimize by being more aggressive about how for these short-lived, locally-scoped objects are deallocated. @autoreleasepool replaces and improves upon the old NSAutoreleasePool, which is significantly slower, and unavailable with ARC.

  2. @synchronized(){}: This directive offers a convenient way to guarantee safe execution of a particular code block within a specified context (usually self ). Locking in this way is expensive, however, so for classes aiming for a particular level of thread safety, a dedicated NSLock property or the use of low-level locking functions like OSAtomicCompareAndSwap32(3) are recommended.

Compatibility

  1. @compatibility_alias: Allows existing classes to be aliased by a different name.

    @compatibility_alias can be used to significantly improve the experience of working with classes across major OS versions, allowing developers to back-port their own custom implementations of new functionality, without changing how that class is used in the app.