使用 arc 将对象添加到其他对象内的容器中为空
我用的是苹果的ARC。我有两个类:一个有 NSMutableSet,另一个我想放入 NSMutableSet 中。
所以当我执行以下操作时:
ContainerClass* contClass = [[ContainerClass alloc] init];
for(int i = 0;i<10;i++)
{
SmallClass* myClass = [[SmallClass alloc] init];
[myClass setinfo:i];
[contClass.mySet addObject:myclass];
}
for(SmallClass* cls in contClass.mySet){
NSLog(@"%@", cls);
}
结果是: (null) (null) (null) (null) 等。
这是否意味着 SmallClass 正在被 ARC 释放?我该如何解决它(当然我不能保留)?在 myclass 实例上调用 copy 会导致错误,因为我没有为 myClass 实现 copy(在 ARC 之前的方式中,我只会保留它)。
ContainerClass代码:
@interface ContainerClass : NSObject {
NSString* _icon;
NSMutableSet* _mySet;
}
@property (nonatomic, strong) NSString* icon;
@property (nonatomic, strong) NSMutableSet* mySet;
@end
和实现:
@implementation ContainerClass
-(id) init
{
_myset = [[NSMutableSet alloc] init];
return [super init];
}
@synthesize mySet = _mySet;
@end
I am using Apple's ARC. I have tow classes: one that has a NSMutableSet and one that I want to put inside that NSMutableSet.
So when I do the following:
ContainerClass* contClass = [[ContainerClass alloc] init];
for(int i = 0;i<10;i++)
{
SmallClass* myClass = [[SmallClass alloc] init];
[myClass setinfo:i];
[contClass.mySet addObject:myclass];
}
for(SmallClass* cls in contClass.mySet){
NSLog(@"%@", cls);
}
the result is: (null) (null) (null) (null) etc.
Does it means that SmallClass is being released by ARC? How can I solve it (I can't do retain of course)? Calling copy on myclass instance results with error because I didn't implement copy for myClass (in the pre-ARC way I would just do retain on it).
ContainerClass code:
@interface ContainerClass : NSObject {
NSString* _icon;
NSMutableSet* _mySet;
}
@property (nonatomic, strong) NSString* icon;
@property (nonatomic, strong) NSMutableSet* mySet;
@end
and the implementation:
@implementation ContainerClass
-(id) init
{
_myset = [[NSMutableSet alloc] init];
return [super init];
}
@synthesize mySet = _mySet;
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你的 ContainerClass init 方法是错误的。尝试以下方法:
希望有帮助。
I think your ContainerClass init method is wrong. Try the following:
Hope it helps.