Here's the first class:
@interface ClassA : NSObject {
NSMutableArray* array1;
NSArray* array2;
}
@property (nonatomic, assign)NSMutableArray* array1;
@property (nonatomic, assign)NSArray* array2;
-(id) initWithData:(NSString*)string1 andWords:(NSString*)string2;
@end
@implementation ClassA
@synthesize array1;
@synthesize array2;
-(id) initWithData:(NSString*)string1 andWords:(NSString*)string2
{
if ((self = [super init]))
{
array1 = [[NSMutableArray alloc] initWithCapacity:[string1 length]];
for (int i=0; i < [array1 length]; i++)
[array1 addObject:[NSString stringWithFormat:@"%c", [string1 characterAtIndex:i]]];
array2 = [string2 componentsSeparatedByString:@";"];
NSLog(@"array1 = %@", array1);
NSLog(@"array2 = %@", array2);
}
return self;
}
- (void) dealloc
{
[array1 release];
[array2 release];
[super dealloc];
}
@end
Here's 2nd Class:
@interface ClassB : NSObject {
ClassA* classA;
}
@property (nonatomic, assign)ClassA* classA;
Im having issues gaining access to the properties of ClassA, that are stored in ClassB.
For instance, I want to do something like:
// print out the arrays stored in Class B
NSLog(@"%@",[[classB classA] array1]);
NSLog(@"%@",[[cl开发者_JAVA技巧assB classA] array2]);
array1 prints out okay, but array2 throws and EXC_BAD_ACCESS error. I'm guessing because
array2 = [string2 componentsSeparatedByString:@";"];
is not allocating properly.
It's much easier to let Apple handle the memory management for you: change your array1
and array2
properties from assign
to retain
and then use the following in your init
:
NSMutableArray* newArray1 = [NSMutableArray arrayWithCapacity:[string1 length]];
for (int i=0; i < [array1 length]; i++)
[array1 addObject:[NSString stringWithFormat:@"%c", [string1 characterAtIndex:i]]];
[self setArray1:newArray1];
[self setArray2:[string2 componentsSeparatedByString:@";"]];
This way, your @synthesize
d setter methods will handle retaining the properties for you.
I believe that array2 is being autoreleased because you are creating it with one of NSString's convenience methods rather then explicitly allocating the array. Try retaining the results instead of just setting your iVar to the autoreleased string.
I resolved this issue by first calling alloc:
array2 = [NSArray alloc];
array2 = [string2 componentsSeparatedByString:@";"];
精彩评论