I've read several posts similar to this one but I found them too specific. What I really want is a more general answer. According to Apple's view controller programming guide, viewDidLoad:
should be used to "Allocating or loading data to be displayed in your view". If I have some data that has nothing to do with display, where should I initialize them?
Some posts suggests that initialization could be done in initWithCoder:
when the view controller is initialized via a storyboard. I've tried to initialize an array in initWithCoder:
, but after that it turned out that the array is still empty. So can we write a designated initializer to initialize this kind of data?
Here is the code:
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
// load notes
NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
_notes = [[PWCNotes alloc] initNotesWithFilename:self.docTitle path:path numberOfPages:self.numberOfPages];
_index = 0;
}
return self;
}
Here is the designated initializer method for PWCNotes
- (id)initNotesWithFilename:(NSString *)fileName path:(NSString *)path numberOfPages:(int)numberOfPages
{
if (!(self = [super init])) {
return nil;
}
_filePath = [path stringByAppendingString:[NSString stringWithFormat:@"/%@/notes.txt", fileName]];
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:self.filePath];
if (!exists)
{
// if file does not exist, create one and initialize the content
_notes = [[NSMutableArray alloc] init];
[[NSFileManager defaultManager] createFileAtPath:self.filePath contents:nil attributes:nil];
NSString * emptyString = @"Add Notes Here!";
for (int i = 0; i < numberOfPages; ++i)
{
[self.notes addObject:emptyString];
}
// write content of the array to the file
[self.notes writeToFile:self.filePath atomically:YES];
}
else
{
// otherwise, load it from the text file
_notes = [[NSMutableArray alloc] initWithContentsOfFile:self.filePath];
}
return self;
}
PWCNotes
class has as a property a mutable array of NSString *
s. When I call [self.notes.notes getObjectAtIndex:self.index]
, an NSRangeException
is thrown, saying that I'm trying to access the object at index 0 in an empty array. Am I missing something?