zou*_*oul 20 properties objective-c
我想声明一个公共不可变属性:
@interface Foo
@property(strong, readonly) NSSet *items;
@end
Run Code Online (Sandbox Code Playgroud)
...在实现文件中以可变类型支持:
@interface Foo (/* private interface*/)
@property(strong) NSMutableSet *items;
@end
@implementation
@synthesize items;
@end
Run Code Online (Sandbox Code Playgroud)
我想要的是实现中的可变集合,当从外部访问时,它会被转换为不可变的集合.(我并不关心调用者是否可以将实例强制转换NSMutableSet并打破封装.我住在一个安静,体面的城镇,这样的事情不会发生.)
现在我的编译器将属性视为NSSet实现内部.我知道有很多方法可以让它工作,例如使用自定义getter,但有没有办法简单地使用声明的属性?
最简单的解决方案是
@interface Foo {
@private
NSMutableSet* _items;
}
@property (readonly) NSSet* items;
Run Code Online (Sandbox Code Playgroud)
然后就是
@synthesize items = _items;
Run Code Online (Sandbox Code Playgroud)
在你的实现文件中.然后你可以通过_items访问可变集,但公共接口将是一个不可变集.
小智 8
您必须将公共接口中的属性声明为readonly,以便编译器不要抱怨.像这样:
Word.h
#import <Foundation/Foundation.h>
@interface Word : NSObject
@property (nonatomic, strong, readonly) NSArray *tags;
@end
Run Code Online (Sandbox Code Playgroud)
Word.m
#import "Word.h"
@interface Word()
@property (nonatomic, strong) NSMutableArray *tags;
@end
@implementation Word
@end
Run Code Online (Sandbox Code Playgroud)
你可以在你的实现中自己做:
@interface Foo : NSObject
@property(nonatomic, retain) NSArray *anArray;
@end
Run Code Online (Sandbox Code Playgroud)
--- 实施文件 ---
@interface Foo()
{
NSMutableArray *_anArray;
}
@end
@implementation Foo
- (NSArray *)anArray
{
return _anArray;
}
- (void)setAnArray:(NSArray *)inArray
{
if ( _anArray == inArray )
{
return;
}
[_anArray release];
_anArray = [inArray retain];
}
- (NSMutableArray *)mutablePrivateAnArray
{
return _anArray;
}
@end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3452 次 |
| 最近记录: |