使用方法和属性有什么区别?
我正在研究“The Elements”示例应用程序的源代码,我在 AtomicElement.h 有四个属性声明为只读:
@property (readonly) UIImage *stateImageForAtomicElementTileView;
@property (readonly) UIImage *flipperImageForAtomicElementNavigationItem;
@property (readonly) UIImage *stateImageForAtomicElementView;
@property (readonly) CGPoint positionForElement;
在实现文件中,它们看起来像
- (UIImage *)stateImageForAtomicElementTileView {
return [UIImage imageNamed:[NSString stringWithFormat:@"%@_37.png",state]];
}
您可以详细说明这样做的原因吗那?为什么不使用类似
- (UIImage*) stateImageForAtomicElementTileView;
头文件中的内容,然后像 [element stateImageForAtomicElementTileView];
而不是 element.stateImageForAtomicElementTileView
那样访问它?
I am studying the source code for "The Elements" sample app and I see that in AtomicElement.h there are four properties declared as readonly:
@property (readonly) UIImage *stateImageForAtomicElementTileView;
@property (readonly) UIImage *flipperImageForAtomicElementNavigationItem;
@property (readonly) UIImage *stateImageForAtomicElementView;
@property (readonly) CGPoint positionForElement;
In the implementation file, they look like
- (UIImage *)stateImageForAtomicElementTileView {
return [UIImage imageNamed:[NSString stringWithFormat:@"%@_37.png",state]];
}
Can you please elaborate on the reasons to do that? Why not use something like
- (UIImage*) stateImageForAtomicElementTileView;
in the header file, and then access it like [element stateImageForAtomicElementTileView];
instead of element.stateImageForAtomicElementTileView
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为没有技术原因来选择一种习语而不是另一种,它们都可以以相同的方式使用。这更多是一个语义问题。
类既具有数据又可以执行操作(通常对所述数据)。我认为您应该考虑使用属性,并使用
.
访问而不是[ ]
更多地作为记录stateImageForAtomicElementTileView
。它是属于类的一部分的图像(事实上不是从资源动态生成的,应该被视为实现细节)
I don't think there's a technical reason to choose one idiom over the other, they can both be used in the same way. It's more a matter of semantics.
A class has both data and can perform operations (usually on said data). I think you should look at using a property, and having the
.
access instead of[ ]
more as a way of documenting the purpose of thestateImageForAtomicElementTileView
.It's an image that's part of the class (the fact is't being generated on the fly from a resource should be seen as an implementation detail)