I have a data structure I am trying to store in objective c for ios5 with ARC.
The data structure is something like –
Class - **Book**
@property (strong) NSArray *pages;
@property (strong) Page *startingPage;
Class - **Page**
@property (strong) Book *book;
@property (strong) Page *nextPage;
@property (strong) Page *previousPage;
The problem as can be imagined is with memory leaks.
There are a couple of cycles here –
Book -> pages -> page -> book
nextPage -> previousPage
Book -> startingPage -> book.
I can’t make the properties weak because if I do so, I’ll lose the pointer to that value.
So suppose I make book in Page as weak, then when I try to deallocate a page, book will get deallocated. However, I still want the book to remain allocated.
Is there any alternate way this data structure can be stored?
Thanks!
I don’t understand why making Page->book
weakwould lose you the pointer to the book. Weak properties aren’t auto-nil’d until the object they point to is deallocated. As long as at least one other object has a strong reference tobookyou should be fine.So imagine a Library object that has an NSArray of books. The array retains the books added to it, so all weak references to that book will stay valid until the book’s removed from the array (and implicitly released).