extension可以认为是匿名的category,但是这个extension相对于category有有一个特殊功能:
在extension中可以定义可写的属性,公有可读、私有可写的属性(Publicly-Readable, Privately-Writeable Properties)一般这样实现!
举例说明如下:
1. 创建测试程序empty application
2. 我们自定义一个UIViewController,命名为RootViewController,它的.h文件为:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
那么在其对应的.m中会自动生成以下代码:
@interface ViewController : UIViewController
@end
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
那么在其对应的.m中会自动生成以下代码:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}3. 第2步中的.m文件中我们能看到@interface ViewController : UIViewController
@end
这个就是extension了(也就是特殊类型的category)
如果我们在.h添加这样一个属性
@property (readonly) float value;
那么RootViewController对外就暴露一个readonly的属性,它是公开的,所以外部是不能够对它进行写操作的。
这时我们可以在extension加入以下代码:
@property (readwrite) float value;
那么这个属性在内部就是可读写的了,如果是只读只能在构造时期对它赋值,其他类方法中是不能对其赋值的。
有了这个特性支持,那么类的内部方法均可以对其进行赋值了。
本文深入探讨了Objective-C中的extension与category概念,解释了它们之间的区别,并通过实例展示了如何在实际开发中利用extension实现可读写属性。文章强调了extension在对象内部属性管理中的优势。
146

被折叠的 条评论
为什么被折叠?



