简体   繁体   English

插入可变数组时如何保留该对象?

[英]How to retain this object when inserting to mutable array?

update: I have found the bug in my copyWithZone method in A. Thanks everyone. 更新:我已经在A的copyWithZone方法中找到了该错误。谢谢大家。

update: sorry, I do have the @properties declared, I thought it was obvious so I skipped them in my OP. 更新:抱歉,我确实声明了@properties,我认为这很明显,因此我在OP中跳过了它们。 Sorry about that. 对于那个很抱歉。

The crash message is: objA was released (zombie) memory when trying to access the str. 崩溃消息是:尝试访问str时objA已释放(僵尸)内存。


My data structure looks like this: 我的数据结构如下所示:

@class A
{
   NSString *str;
}
@property (retain) NSString *str;  // str synthesized in .m


@class B
{
   A *objA;
}
@property (copy) A *objA;  // objA synthesized in .m

What I am trying to do is: 我正在尝试做的是:

B *newB = [[B alloc] init];
[someMutableArray addObject: newB];

However, I will crash some times when I try to access like this: 但是,当我尝试像这样访问时,我有时会崩溃:

B *myB = [someMutableArray objectAtIndex: index];

someLabel.text = myB.objA.str;

I guess the objA & objA.str were not retained when inserting B into the array. 我猜想在将B插入数组时objA和objA.str没有保留。 But I don't know how to make sure they are retrain. 但是我不知道如何确保他们得到再培训。

Any help is appreciated 任何帮助表示赞赏

-Leo -狮子座

You should be using properties for Class A and B: 您应该为A类和B类使用属性:

@interface A : NSObject {
    NSString *str;
}

@property (nonatomic, retain) NSString *str;
@end

The use @synthesize str; 使用@synthesize str; in .m file, this will retain the str, don't forget to release the str in the dealloc method: 在.m文件中,这将保留str,不要忘了在dealloc方法中释放str:

@implementation A 

@synthesize str;

- (void) dealloc { 
   [str release], str= nil; 
   [super dealloc]; 
}

@end;

你有没有尝试过:

[someMutableArray addObject: [newB copy] ];

At this line 在这条线

someLabel.text = myB.A.str;

it should be... 它应该是...

someLabel.text = myB.objA.str;

Yes, also you should be using properties for the members of your class. 是的,您还应该为类的成员使用属性。 That will retain them. 那将保留他们。 Just don't forget to release in dealloc 只是不要忘记在dealloc中释放

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM