行为 - 在编译时或运行时 - 在此代码之间是否存在任何差异...
// MyClass.h
@interface MyClass : NSObject
@property (nonatomic) SomeType myProperty;
@end
// MyClass.m
@implementation MyClass
@end
Run Code Online (Sandbox Code Playgroud)
......和这段代码?
// MyClass.h
@interface MyClass : NSObject
-(SomeType)myProperty;
-(void)setMyProperty:(SomeType)myProperty;
@end
// MyClass.m
@implementation MyClass {
SomeType _myProperty;
}
-(SomeType)myProperty {
return _myProperty;
}
-(void)setMyProperty:(SomeType)myProperty {
_myProperty = myProperty;
}
@end
Run Code Online (Sandbox Code Playgroud)
显然,前一版本更简洁,更易读,但行为有什么不同吗?合成的getter和setter是否做了比我直接实现更复杂的事情?内省函数是否可以通过声明getter和setter来区分属性的声明?还有其他我没有想到的差异吗?
简短的回答: 没有区别.但是,某些属性(copy或atomic)可能需要不同的访问器方法.
答案很长:有一组内省函数允许您访问@properties为给定类或协议声明的所有内容:
class_getProperty
class_copyPropertyList
protocol_getProperty
protocol_copyPropertyList
property_getName
property_getAttributes
Run Code Online (Sandbox Code Playgroud)
我不认为这些函数中的任何一个在生产代码中都有用,因为这基本上是类的实现细节.此外,可能在公共接口中公开了getter/setter,在类扩展中隐藏了私有属性.
哦,还有另外一个区别:Xcode以不同的方式突出显示属性和普通的getter :)
| 归档时间: |
|
| 查看次数: |
255 次 |
| 最近记录: |