Objective-C –在类中执行 NSMutableArray 操作但返回 NSArray
我很抱歉这个有点令人困惑的标题,但我有一个类,其接口如下所示:
@interface Class : NSObject {
NSArray *items;
}
@property (nonatomic, retain) NSArray *items;
@end
在实现中,我实际上想做一些添加操作,因此使用 NSMutableArray
,然后用户使用类应该能够以 NSArray
形式检索数据。
I'm sorry for the little confusing title but say I have a class with an interface that looks like this:
@interface Class : NSObject {
NSArray *items;
}
@property (nonatomic, retain) NSArray *items;
@end
In the impementation I actually want to do some adding operations thus using NSMutableArray
and then the user using the class should be able to retrieve the data as an NSArray
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将可变数组声明为实例变量,将属性声明为只读 NSArray 并覆盖 getter。
Declare mutable array as instance variable, declare the property as readonly NSArray and overwrite the getter.
没有什么理由不从声明为返回 NSArray 的方法中返回 NSMutableArray。
There is little reason not to just return an NSMutableArray from a method declared as returning an NSArray.
如果您不希望用户更改数组,您可以这样做:
Well if you don't want the user to change the array you can just do it like this:
您可以简单地将变量定义为您想要的类型,而不是为实例变量定义属性:
并将其用作
NSMutableArray
:但是然后在您的界面中,定义一个 getter 方法返回一个 NSArray:
并按如下方式实现它:
Instead of defining a property for your instance variable, you could simply define the variable as the type you want it to be:
And use it as an
NSMutableArray
:But then in your interface, define a getter method that returns an
NSArray
:And implement it as such: