简体   繁体   中英

How to retain this object when inserting to mutable array?

update: I have found the bug in my copyWithZone method in A. Thanks everyone.

update: sorry, I do have the @properties declared, I thought it was obvious so I skipped them in my OP. Sorry about that.

The crash message is: objA was released (zombie) memory when trying to access the str.


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. 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:

@interface A : NSObject {
    NSString *str;
}

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

The use @synthesize str; in .m file, this will retain the str, don't forget to release the str in the dealloc method:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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