0
votes

I'm attempting to initialize an array and add a chapter object to an array of book objects, but it crashes with the error:

2012-07-25 21:41:01.503 Project1[2364:f803] -[__NSCFString arrayOfChapters]: unrecognized selector sent to instance 0x6ad80b0 2012-07-25 21:41:01.505 Project1[2364:f803] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString arrayOfChapters]: unrecognized selector sent to instance 0x6ad80b0'

My code:

Chapter *myChapter = [[Chapter alloc]init];
myChapter.pageCount = self.TextField2.text;
myChapter.chapterTitle = self.TextField1.text;
if(!currentBook.arrayOfChapters)
{
    currentBook.arrayOfChapters = [[NSMutableArray alloc]init];
}
currentBook = [books objectAtIndex:segControl.selectedSegmentIndex];
[currentBook.arrayOfChapters addObject:myChapter];

I think the code is correct, is there something set up wrong with my project? I believe it's the initialization which is causing the actual crash, but there isn't anything non-standard there.

3
Where do you declare arrayOfChapters?pasawaya
In the class Book: @property(nonatomic, strong) NSMutableArray *arrayOfChapters;Tasonir
Do you initialize currentBook anywhere before the line currentBook = [books objectAtIndex:segControl.selectedSegmentIndex];?Ethan Holshouser
currentBook is a local variable which is initialized in the line of code on screen - which is just after I check if it's null. I've moved that line of code above the if statement, but it still crashes with the same error.Tasonir
You can't refer to a property (arrayOfChapters) of an item that's not, itself, initialized. You want to check currentBook before you start using it.Rob

3 Answers

1
votes

you can make a breakpoint on the line "if(!currentBook.arrayOfChapters)" to check whether the currentBook is nil;

make a breakpoint on the line"currentBook = [books objectAtIndex:segControl.selectedSegmentIndex]; " to check whether the segControl.selectedSegmentIndex >= [books count]

1
votes

It looks like currentBook is a string or not initialized.

0
votes

I may be misreading this but...

    if(!currentBook.arrayOfChapters)
    {
        // creating array for current book
        currentBook.arrayOfChapters = [[NSMutableArray alloc]init]; 
    }

    // reassigning a new book to current book. Are you sure this new one has array of chapters?
    currentBook = [books objectAtIndex:segControl.selectedSegmentIndex]; 

    // trying to access array of chapters
    [currentBook.arrayOfChapters addObject:myChapter]; 

Shouldn't you be assigning first and then creating array if it's not already there?