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 notationperson->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 anNSString
object initialized with the Unicode content inside the quotation marks. -
@42
,@3.14
,@YES
,@'Z'
: Returns anNSNumber
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 anNSArray
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 sentinelnil
is not required in literal). -
@{}
: Returns anNSDictionary
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
forconst char*
,NSNumber
forint
, etc.). This is also the designated way to use number literals withenum
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 anSEL
pointer to a selector with the specified name. Used in methods like-performSelector:withObject:
. -
@protocol()
: Returns aProtocol *
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 struct
s? 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 inNSCoder -encodeValueOfObjCType:at
. -
@defs()
: Returns the layout of an Objective-C class. For example, to declare a struct with the same fields as anNSObject
, 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 oldNSAutoreleasePool
, 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 (usuallyself
). Locking in this way is expensive, however, so for classes aiming for a particular level of thread safety, a dedicatedNSLock
property or the use of low-level locking functions likeOSAtomicCompareAndSwap32(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.
相关推荐
这是关于无线终端所使用的at指令的一些注意事项。
@符号一直不知道是什么意思,其实它是错误控制符,即即使出现错误,也无视出现的错误信息,继续执行下边的代码
AT@T汇编语言指南,比较简单的指南,能快速上手。需要稍微有一点基础。
STM32+通信模组的通用AT指令框架,简单修改即可移植。
1. Modified parameter <mode> of AT+QLWULDATAEX (added RELEASE_AFTER_REPLY RAI flag). 2. Added note: network attachment should be triggered by AT+CGATT=1 but not AT+CFUN=1 in Chapter 3.17. 3. Modified ...
TCL AT848,AT16120话机TCL AT848,AT16120话机编程说明书编程说明书TCL AT848,AT16120话机编程说明书
AT中文指令AT中文指令AT中文指令AT中文指令AT中文指令AT中文指令AT中文指令AT中文指令AT中文指令AT中文指令AT中文指令
AT编程 AT命令集 AT命令 AT编程 AT命令集 AT命令
雅特力_AT-START-F403A(AT32F403AVGT7)单片机开发板用户手册+KEIL软件代码,国产MCU芯片,可供开发及学习参考。 AT-START-F403A帮助你探索发现带有FPU内核ARM Cortex-M4F 32位处理器AT32F403A的高性能特性,并帮助...
x557-at-at2-at4-10gbe-phy-datasheet The Intel® X557-AT/AT2/AT4 10 GbE PHY (X557) is a single (AT), dual (AT2), quad (AT4) port, 28 nm CMOS 10GBASE-T / 1000BASE-T / 100BASE-TX triple-speed PHY that is...
雅特力的AT32F435/437,最高主频288MHZ,FLASH可以达到4M,价格却很低,比起STM32简直不要太香。 STM32可以有STM32CubeMX轻松移植THreadX,雅特力从AT43F435/437系列开始不能完全兼容STM32,用不了THreadX了。 本...
一 AT指令基本用法: 1. 测试命令(Test Command) 在AT指令后面加上"=?"即构成测试命令。例如"AT+CSCS=?"会列举出所有支持的字符集。 2. 读取命令(Read Command) 在AT指令后面加上"?"即构成读取命令。例如"AT...
AT1846S V0.2 Datasheet
linux下的AT24C02驱动,采用了palrform形式,基于这个版本bus devcie driver
适用产品有:智能机、功能机、无屏模块类、WCN产品、CIOT产品,主要功能包括: (1)模拟常用界面(拨号盘、网络信息、工模等) (2)AT命令测试(AT收发、AT命令集创建、AT命令集测试) (3)自动化测试(基于...
基于STM32103 AT24C64~256驱动程序
AT华为工具1.8安装包AT华为工具1.8安装包AT华为工具1.8安装包AT华为工具1.8安装包AT华为工具1.8安装包AT华为工具1.8安装包AT华为工具1.8安装包AT华为工具1.8安装包AT华为工具1.8安装包AT华为工具1.8安装包AT华为工具...
海德汉ENDAT2.2协议,CRC校验C代码,调试通过,绝对可用
这是基于STM32设计的AT24C02与AT24C08_EEPROM存储芯片驱动代码,包含了IIC模拟时序、IIC硬件时序两种方式驱动。 包含了AT24C02、AT24C08两款芯片的代码。