60 likes | 170 Views
In this chapter, we explore how to dynamically manage tags in our iOS application by writing to and reading from a file. We utilize the `filePath` variable in the initialization method to read existing tags from `tagsIndex.plist`. If data is found, we initialize tags accordingly. Inside the `viewDidLoad`, we loop through the tags and create buttons for each. The `addTag` method allows us to modify our tags and overwrite the file, maintaining data persistence between app runs. This approach ensures that added buttons are remembered even after closing and reopening the app.
E N D
Chapter 5 – Step 2 Dynamic data • Now when we add a tag, we will write it to a file • And when we start the app, we will read from that file
Controller.h • We will now make use of the filePath instance variable • In the init method, we will try to read from the file storing the tags • If there is data, we will initialize tags with the data
Init method • Go through same procedure as before to read from a file • Use name tagsIndex.plist for the file • If we find the file, then we initialize tags with its contents tags = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
viewDidLoad • Inside viewDidLoad (called when view has loaded) /* loop through all the tags, add a button for each of them */ for( NSString *title in tags ) [self addNewButtonWithTitle:title];
addTag method After we add a tag to tags, we need to overwrite the file with tags We can write an entire dictionary at a time [tags writeToFile: filePath atomically:NO];
Run the app Run the app and save buttons Close the app, run again • Saved buttons should come up