[英]Instance variable access in objective-c class method
I wonder how can I do a thing that I always done in Java. 我想知道如何做我一直用Java做的事情。
public class ObjectHolder {
private List<Object> holder;
public ObjectHolder() {
// initialize object holder...
}
public boolean addObject(Object obj) {
// add object and return true/false
}
}
The good of this approach is that holder is not accessible for direct manipulation. 这种方法的好处是无法直接操作持有人。 I am trying to understand how this can be achieved in Objective-c, in particular I made this Objective-c class interface: 我试图了解如何在Objective-c中实现这一目标,尤其是我创建了这个Objective-c类接口:
@interface ObjectHolder : NSObject {
NSMutableArray *holder;
}
+(ObjectHolder*)holderWithObjects:(NSArray*)objs;
-(BOOL)addObject:(NSObject*)obj;
@end
But this is where my questions start, in particular within the class method holderWithObjects: 但这是我的问题开始的地方,尤其是在类方法holderWithObjects中:
+(ObjectHolder*)holderWithObjects:(NSArray*)objs {
ObjectHolder *oh = [[[ObjectHolder alloc] init] autorelease];
oh->holder= // array initialization and retain
for(NSObject obj in objs) {
// add to holder array
[oh->holder addObject:obj];
}
return oh;
}
You can do it eg like this: 您可以这样做,例如:
.h file: .h文件:
@interface ObjectHolder : NSObject {
NSMutableArray *holder;
}
+(ObjectHolder*)holderWithObjects:(NSArray*)objs;
-(void)addObject:(id)obj;
@end
.m file: .m文件:
+ (ObjectHolder*)holderWithObjects:(NSArray*)objs {
ObjectHolder *oh = [[[ObjectHolder alloc] init] autorelease];
for(id obj in objs) {
[oh addObject:obj];
}
return oh;
}
- (void)addObject:(id)obj {
if (holder == nil) {
holder = [[NSMutableArray alloc] init];
}
[holder addObject:obj];
}
- (void)dealloc {
[holder release];
[super dealloc];
}
Some notes: 一些注意事项:
NSMutableArray
's -addObject:
returns void, so there's really no use in returning BOOL
from your method, unless you want some specific behaviour (like avoiding duplicates in the array - then maybe NSSet
would be better?, etc.) NSMutableArray
的-addObject:
返回void,因此从您的方法返回BOOL
确实没有用,除非您想要某些特定的行为(例如避免在数组中重复-否则NSSet
会更好?等)。 id
is more general than NSObject *
and in most cases you would prefer using it, see this blog post for more info id
比NSObject *
更通用,在大多数情况下,您希望使用它,有关更多信息,请参见此博客文章 。 nil
by default, so you can check in your -addObject:
for holder value and lazily initialize it when it's needed. 缺省情况下,作为Objective-C对象的实例变量为nil
,因此您可以在-addObject:
检入holder值,并在需要时延迟对其进行初始化。 Otherwise you can simply initialize holder
in -init
method - that is the equivalent of a constructor in Java 否则,你可以简单地初始化holder
在-init
方法-这是在Java中的构造相当于 -dealloc
method 您必须在-dealloc
方法中释放Holder数组 -addObjects:(NSArray *)objs
that would help you to avoid iterating through the array and adding objects one by one 您可以考虑使用-addObjects:(NSArray *)objs
类的方法,该方法将帮助您避免遍历数组并一个接一个地添加对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.