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.tex开发者_开发技巧t = 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;
You should look in to
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html%23//apple_ref/doc/uid/TP30001163-CH17
to learn about properties and how they manage memory.
Have you tried:
[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
精彩评论