简体   繁体   中英

Why is my object nil when I get it from a NSMutableArray?

I'm having a problem with this code here

Book *theNewBook = [self parseTheBookXML];
// The book is not nil here
NSLog(@"The book's title: %@, number of pages:%@ and author: %@",theNewBook.title, theNewBook.pages, theNewBook.author);

[_theBooksArray addObject:theNewBook];

// TEST
Book *testBook = [_theBooksArray objectAtIndex:0];
// The book is nil here
NSLog(@"The book's title: %@, number of pages:%@ and author: %@",testBook.title, testBook.pages, testBook.author);

Can anyone tell me why my book object is 'nil' because I've hit a wall over here...

As you can see from the comments on my question my problem was that I had not initialized the array I was accessing. So INSTEAD of

[_theBooksArray addObject:theNewBook];

calling

_theBooksArray = [[NSMutableArray alloc] initWithObjects:theNewBook, nil];

will do the trick.

[_theBooksArray addObject:theNewBook];
[_theBooksArray count];

print the log and check the array count.

You Must Init The Array Before Using it.

_theBooksArray = [[NSMutableArray alloc] init];

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