I am trying to populate an NSMutableArray here named “data” with NSArrays. When I try to retrieve I get EXC_BAD_ACCESS. Here is my code for poulating
.h
@property (nonatomic, retain) NSMutableArray* data;
.m
@synthesize data;
in viewDidLoad
self.data = [NSMutableArray array];
NSArray* ar1 = [[NSArray arrayWithObjects: @"text1", @"text2", @"text3", @"text4", nil] autorelease];
[self.data addObject:ar1];
Now in other method I am trying to get the inner NSArray back:
NSArray* sItem = [NSArray array];
sItem = (NSArray*)[self.data objectAtIndex:0];
if (sItem)
{
if([sItem isKindOfClass:[NSArray class]])/////ERROR LINE
{
NSLog(@"Its an Array.");
}
}
In
-viewDidLoad, you are over-releasingar1. It is returned already autoreleased. You know this because you obtained the array viaarrayWithObjects:, not byalloc/init.The pattern is:
or
You should switch your project to ARC–it will handle this for you.
EDIT:
You can also rewrite
as
or even
Notes about your code:
NSArrayand assigning it to the pointersItem. This array is immediately discarded when you assign another value tosItem. Just initializesItemtonilinstead.if (sItem)… Sending-isKindOfClass:(or any message in fact) tonilwill always returnNO/nil/0.Finally, I often check for the presence of an array by doing something like:
This shortcut is especially good for strings.