`
慭慭流觞
  • 浏览: 44042 次
  • 性别: Icon_minigender_1
  • 来自: 河南
社区版块
存档分类
最新评论

@ at

    博客分类:
  • iOS
阅读更多

Interface & Implementation

@interface and @implementation are the first things you learn about when you start Objective-C:

  • @interface...@end
  • @implementation...@end

What you don't learn about until later on, are categories and class extensions.

Categories allow you to extend the behavior of existing classes by adding new class or instance methods. As a convention, categories are defined in their own .{h,m} files, like so:

MyObject+CategoryName.h

@interface MyObject (CategoryName)
  - (void)foo;
  - (BOOL)barWithBaz:(NSInteger)baz;
@end

MyObject+CategoryName.m

@implementation MyObject (CategoryName)
  - (void)foo {
    // ...
  }

  - (BOOL)barWithBaz:(NSInteger)baz {
    return YES;
  }
@end

Categories are particularly useful for convenience methods on standard framework classes (just don't go overboard with your utility functions).

Pro Tip: Rather than littering your code with random, arbitrary color values, create an NSColor / UIColor color palette category that defines class methods like +appNameDarkGrayColor. You can then add a semantic layer on top of that by creating method aliases like +appNameTextColor, which returns +appNameDarkGrayColor.

Extensions look like categories, but omit the category name. These are typically declared before an @implementation to specify a private interface, and even override properties declared in the interface:

@interface MyObject ()
@property (readwrite, nonatomic, strong) NSString *name;
- (void)doSomething;
@end

@implementation MyObject
@synthesize name = _name;

// ...

@end

Properties

Property directives are likewise concepts learned early on:

  • @property
  • @synthesize
  • @dynamic

One interesting note with properties is that as of Xcode 4.4, it is no longer necessary to explicitly synthesize properties. Properties declared in an @interface are automatically synthesized (with leading underscore ivar name, i.e. @synthesize propertyName = _propertyName) in the implementation.

Forward Class Declarations

Occasionally, @interface declarations will reference an external class in a property or as a parameter type. Rather than adding #import statements for each class, it's good practice to use forward class declarations in the header, and import them in the implementation.

  • @class

Shorter compile times, less chance of cyclical references; you should definitely get in the habit of doing this if you aren't already.

Instance Variable Visibility

It's a matter of general convention that classes provide state and mutating interfaces through properties and methods, rather than directly exposing ivars.

Although ARC makes working with ivars much safer by taking care of memory management, the aforementioned automatic property synthesis removes the one place where ivars would otherwise be declared.

Nonetheless, in cases where ivars are directly manipulated, there are the following visibility directives:

  • @public: instance variable can be read and written to directly, using the notation person->age = 32"
  • @package: instance variable is public, except outside of the framework in which it is specified (64-bit architectures only)
  • @protected: instance variable is only accessible to its class and derived classes
  • @private: instance variable is only accessible to its class
@interface Person : NSObject {
  @public
  NSString name;
  int age;

  @private
  int salary;
}

Protocols

There's a distinct point early in an Objective-C programmer's evolution, when she realizes that she can define her own protocols.

The beauty of protocols is that they allow programmers to design contracts that can be adopted outside of a class hierarchy. It's the egalitarian mantra at the heart of the American Dream: that it doesn't matter who you are, or where you come from: anyone can achieve anything if they work hard enough.

...or at least that's idea, right?

  • @protocol...@end: Defines a set of methods to be implemented by any class conforming to the protocol, as if they were added to the interface of that class.

Architectural stability and expressiveness without the burden of coupling--protocols are awesome.

Requirement Options

You can further tailor a protocol by specifying methods as required or optional. Optional methods are stubbed in the interface, so as to be auto-completed in Xcode, but do not generate a warning if the method is not implemented. Protocol methods are required by default.

The syntax for @required and @optional follows that of the visibility macros:

@protocol CustomControlDelegate
  - (void)control:(CustomControl *)control didSucceedWithResult:(id)result;
@optional
  - (void)control:(CustomControl *)control didFailWithError:(NSError *)error;
@end

Exception Handling

Objective-C communicates unexpected state primarily through NSError. Whereas other languages would use exception handling for this, Objective-C relegates exceptions to truly exceptional behavior, including programmer error.

@ directives are used for the traditional convention of try/catch/finally blocks:

@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];
} 

Literals

Literals are shorthand notation for specifying fixed values. Literals are more -or-less directly correlated with programmer happiness. By this measure, Objective-C has long been a language of programmer misery.

Object Literals

Until recently, Objective-C only had literals for NSString. But with the release of the Apple LLVM 4.0 compiler, literals for NSNumber, NSArray and NSDictionary were added, with much rejoicing.

  • @"": Returns an NSString object initialized with the Unicode content inside the quotation marks.
  • @42, @3.14, @YES, @'Z': Returns an NSNumber object initialized with pertinent class constructor, such that @42[NSNumber numberWithInteger:42], or @YES[NSNumber numberWithBool:YES]. Supports the use of suffixes to further specify type, like @42U[NSNumber numberWithUnsignedInt:42U].
  • @[]: Returns an NSArray object initialized with the comma-delimited list of objects as its contents. For example, @[@"A", @NO, @2.718][NSArray arrayWithObjects:@"A", @NO, @2.718, nil] (note that sentinel nil is not required in literal).
  • @{}: Returns an NSDictionary object initialized with the specified key-value pairs as its contents, in the format: @{@"someKey" : @"theValue"}.
  • @(): Dynamically evaluates the boxed expression and returns the appropriate object literal based on its value (i.e. NSString for const char*, NSNumber for int, etc.). This is also the designated way to use number literals with enum values.

Objective-C Literals

Selectors and protocols can be passed as method parameters. @selector() and @protocol() serve as pseudo-literal directives that return a pointer to a particular selector (SEL) or protocol (Protocol *).

  • @selector(): Returns an SEL pointer to a selector with the specified name. Used in methods like -performSelector:withObject:.
  • @protocol(): Returns a Protocol * pointer to the protocol with the specified name. Used in methods like -conformsToProtocol:.

C Literals

Literals can also work the other way around, transforming Objective-C objects into C values. These directives in particular allow us to peek underneath the Objective-C veil, to begin to understand what's really going on.

Did you know that all Objective-C classes and objects are just glorified structs? Or that the entire identity of an object hinges on a single isa field in that struct?

For most of us, at least most of the time, coming into this knowledge is but an academic exercise. But for anyone venturing into low-level optimizations, this is simply the jumping-off point.

  • @encode(): Returns the type encoding of a type. This type value can be used as the first argument encode in NSCoder -encodeValueOfObjCType:at.
  • @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) 
}

Ed. As pointed out by readers @secboffin & @ameaijou, @defs is unavailable in the modern Objective-C runtime.

Optimizations

There are some @ compiler directives specifically purposed for providing shortcuts for common optimizations.

  • @autoreleasepool{}: If your code contains a tight loop that creates lots of temporary objects, you can use the @autorelease directive to optimize for these short-lived, locally-scoped objects by being more aggressive about how they're deallocated. @autoreleasepool replaces and improves upon the old NSAutoreleasePool, which is significantly slower, and unavailable with ARC.
  • @synchronized(){}: This directive offers a convenient way to guarantee the safe execution of a particular 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

In case all of the previous directives were old hat for you, there's a strong likelihood that you didn't know about this one:

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

For example PSTCollectionView uses @compatibility_alias to significantly improve the experience of using the backwards-compatible, drop-in replacement for UICollectionView:

// Allows code to just use UICollectionView as if it would be available on iOS SDK 5.
// http://developer.apple.    com/legacy/mac/library/#documentation/DeveloperTools/gcc-3.   3/gcc/compatibility_005falias.html
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 60000
@compatibility_alias UICollectionViewController PSTCollectionViewController;
@compatibility_alias UICollectionView PSTCollectionView;
@compatibility_alias UICollectionReusableView PSTCollectionReusableView;
@compatibility_alias UICollectionViewCell PSTCollectionViewCell;
@compatibility_alias UICollectionViewLayout PSTCollectionViewLayout;
@compatibility_alias UICollectionViewFlowLayout PSTCollectionViewFlowLayout;
@compatibility_alias UICollectionViewLayoutAttributes     PSTCollectionViewLayoutAttributes;
@protocol UICollectionViewDataSource <PSTCollectionViewDataSource> @end
@protocol UICollectionViewDelegate <PSTCollectionViewDelegate> @end
#endif

Using this clever combination of macros, a developer can develop with UICollectionView by including PSTCollectionView--without worrying about the deployment target of the final project. As a drop-in replacement, the same code works more-or-less identically on iOS 6 as it does on iOS 4.3.


So to review:

Interfaces & Implementation

  • @interface...@end
  • @implementation...@end
  • @class

Instance Variable Visibility

  • @public
  • @package
  • @protected
  • @private

Properties

  • @property
  • @synthesize
  • @dynamic

Protocols

  • @protocol
  • @required
  • @optional

Exception Handling

  • @try
  • @catch
  • @finally
  • @throw

Object Literals

  • @""
  • @42, @3.14, @YES, @'Z'
  • @[]
  • @{}
  • @()

Objective-C Literals

  • @selector()
  • @protocol()

C Literals

  • @encode()
  • @defs()

Optimizations

  • @autoreleasepool{}
  • @synchronized{}

Compatibility

  • @compatibility_alias

Thus concludes this exhaustive rundown of the many faces of @. It's a versatile, power-packed character, that embodies the underlying design and mechanisms of the language.

 
分享到:
评论

相关推荐

    关于__Federico Milano 的电力系统分析工具箱.zip

    1.版本:matlab2014/2019a/2021a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    mlab-upenn 研究小组的心脏模型模拟.zip

    1.版本:matlab2014/2019a/2021a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    混合图像创建大师matlab代码.zip

    1.版本:matlab2014/2019a/2021a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    中序遍历二叉树-java版本

    在Java中,实现二叉树的中序遍历同样可以通过递归来完成。中序遍历的顺序是:首先递归地中序遍历左子树,然后访问根节点,最后递归地中序遍历右子树。 在这段代码中,Node类定义了二叉树的节点,BinaryTree类包含一个指向根节点的指针和inOrder方法,用于递归地进行中序遍历。printInOrder方法调用inOrder方法并打印出遍历的结果。 在Main类中,我们创建了一个示例二叉树,并调用printInOrder方法来输出中序遍历的结果。输出应该是:4 2 5 1 3,这表示中序遍历的顺序是左子树(4),然后是根节点(2),接着是右子树的左子树(5),然后是右子树的根节点(1),最后是右子树的右子树(3)。

    无头单向非循环链表的实现(SList.c)

    无头单向非循环链表的实现(函数定义文件)

    两个有序链表的合并pta

    "PTA" 通常指的是一种在线编程平台,例如“Pata”或者某些特定学校或组织的编程练习与自动评测系统。在这种平台或系统中,学生或程序员会提交代码来解决各种问题,然后系统会自动运行并评测这些代码的正确性。 当提到“两个有序链表的合并PTA”时,这通常意味着在PTA平台上解决一个特定的问题,即合并两个有序链表。具体任务可能是给定两个已按升序排序的链表,要求编写代码来合并这两个链表,形成一个新的有序链表。

    在 Matlab 中创建的图形工具可改善航空航天数据的可视化.zip

    1.版本:matlab2014/2019a/2021a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    搜索引擎的设计与实现.zip

    搜索引擎的设计与实现

    年公司财务会计岗位工作总结(二).docx

    工作总结,新年计划,岗位总结,工作汇报,个人总结,述职报告,范文下载,新年总结,新建计划。

    【基于Springboot+Vue的Java毕业设计】无人超市管理系统项目实战(源码+录像演示+说明).rar

    【基于Springboot+Vue的Java毕业设计】无人超市管理系统项目实战(源码+录像演示+说明).rar 【项目技术】 开发语言:Java 框架:Spingboot+vue 架构:B/S 数据库:mysql 【演示视频-编号:314】 https://pan.quark.cn/s/8dea014f4d36 【实现功能】 无人超市管理系统有管理员,用户两个角色。管理员功能有个人中心,用户管理,商品类型管理,支付类型管理,公告类型管理,商品信息管理,出入库管理,出入库详情管理,购买管理,购买详情管理,公告信息管理。用户可以注册登录,自助购买,点击购买管理里面收银就可以选择支付类型和商品然后提交,还可以查看购买详情和公告信息。

    电视的半盲图像去模糊问题,.zip

    1.版本:matlab2014/2019a/2021a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    公司年会基本流程表.doc

    年会班会资料,节目策划,游戏策划,策划案,策划方案,活动方案,筹办,公司年会,开场白,主持人,策划主题,主持词,小游戏。

    5G智慧港口解决方案.pptx

    在现有省、市港口信息化系统进行有效整合基础上,借鉴新 一代的感知-传输-应用技术体系,实现对码头、船舶、货物、重 大危险源、危险货物装卸过程、航管航运等管理要素的全面感知、 有效传输和按需定制服务,为行政管理人员和相关单位及人员提 供高效的管理辅助,并为公众提供便捷、实时的水运信息服务。 建立信息整合、交换和共享机制,建立健全信息化管理支撑 体系,以及相关标准规范和安全保障体系;按照“绿色循环低碳” 交通的要求,搭建高效、弹性、高可扩展性的基于虚拟技术的信 息基础设施,支撑信息平台低成本运行,实现电子政务建设和服务模式的转变。 实现以感知港口、感知船舶、感知货物为手段,以港航智能 分析、科学决策、高效服务为目的和核心理念,构建“智慧港口”的发展体系。 结合“智慧港口”相关业务工作特点及信息化现状的实际情况,本项目具体建设目标为: 一张图(即GIS 地理信息服务平台) 在建设岸线、港口、港区、码头、泊位等港口主要基础资源图层上,建设GIS 地理信息服务平台,在此基础上依次接入和叠加规划建设、经营、安全、航管等相关业务应用专题数据,并叠 加动态数据,如 AIS/GPS/移动平台数据,逐步建成航运管理处 "一张图"。系统支持扩展框架,方便未来更多应用资源的逐步整合。 现场执法监管系统 基于港口(航管)执法基地建设规划,依托统一的执法区域 管理和数字化监控平台,通过加强对辖区内的监控,结合移动平 台,形成完整的多维路径和信息追踪,真正做到问题能发现、事态能控制、突发问题能解决。 运行监测和辅助决策系统 对区域港口与航运业务日常所需填报及监测的数据经过科 学归纳及分析,采用统一平台,消除重复的填报数据,进行企业 输入和自动录入,并进行系统智能判断,避免填入错误的数据, 输入的数据经过智能组合,自动生成各业务部门所需的数据报 表,包括字段、格式,都可以根据需要进行定制,同时满足扩展 性需要,当有新的业务监测数据表需要产生时,系统将分析新的 需求,将所需字段融合进入日常监测和决策辅助平台的统一平台中,并生成新的所需业务数据监测及决策表。 综合指挥调度系统 建设以港航应急指挥中心为枢纽,以各级管理部门和经营港 口企业为节点,快速调度、信息共享的通信网络,满足应急处置中所需要的信息采集、指挥调度和过程监控等通信保障任务。 设计思路 根据项目的建设目标和“智慧港口”信息化平台的总体框架、 设计思路、建设内容及保障措施,围绕业务协同、信息共享,充 分考虑各航运(港政)管理处内部管理的需求,平台采用“全面 整合、重点补充、突出共享、逐步完善”策略,加强重点区域或 运输通道交通基础设施、运载装备、运行环境的监测监控,完善 运行协调、应急处置通信手段,促进跨区域、跨部门信息共享和业务协同。 以“统筹协调、综合监管”为目标,以提供综合、动态、实 时、准确、实用的安全畅通和应急数据共享为核心,围绕“保畅通、抓安全、促应急"等实际需求来建设智慧港口信息化平台。 系统充分整合和利用航运管理处现有相关信息资源,以地理 信息技术、网络视频技术、互联网技术、移动通信技术、云计算 技术为支撑,结合航运管理处专网与行业数据交换平台,构建航 运管理处与各部门之间智慧、畅通、安全、高效、绿色低碳的智 慧港口信息化平台。 系统充分考虑航运管理处安全法规及安全职责今后的变化 与发展趋势,应用目前主流的、成熟的应用技术,内联外引,优势互补,使系统建设具备良好的开放性、扩展性、可维护性。

    【基于Java+Springboot的毕业设计】线上医院挂号系统(源码+演示视频+说明).rar

    【基于Java+Springboot的毕业设计】线上医院挂号系统(源码+演示视频+说明).rar 【项目技术】 开发语言:Java 框架:Spingboot+vue 架构:B/S 数据库:mysql 【演示视频-编号:300】 https://pan.quark.cn/s/8dea014f4d36 【实现功能】 本次开发的线上医院挂号系统实现了字典管理、论坛管理、会员管理、单页数据管理、医生管理、医生留言管理、医生挂号订单管理、管理员管理等功能。

    年网通营业员个人工作总结.docx

    工作总结,新年计划,岗位总结,工作汇报,个人总结,述职报告,范文下载,新年总结,新建计划。

    财务数据分析模型3.xlsx

    Excel数据看板,Excel办公模板,Excel模板下载,Excel数据统计,数据展示

    最全英语六级真题(从12年到23年总共66个真题)

    最全英语六级真题,从12年到23年总共66个真题。全网最全。

    财务助理实习总结(2).docx

    工作总结,新年计划,岗位总结,工作汇报,个人总结,述职报告,范文下载,新年总结,新建计划。

    基于深度学习的人体姿态识别.zip

    基于深度学习的人体姿态识别.zip

    01. XX塑业有限公司ERP物料编码规则(DOC 6页).doc

    01. XX塑业有限公司ERP物料编码规则(DOC 6页).doc

Global site tag (gtag.js) - Google Analytics