Sorry that my question is not as clear as I thought:
Is it possible to use NSJSONSerialization to save json data as json file specifically into iPad? I am developing for ios6.
I understand that you can convert it into NSDictionary and NSArray then save it into plist. But what I am looking for is to have a json file in your ios device, that allow to read and write.
Is that possible? Thanks!
Yes, you can use NSJSONSerialization to convert standard collection (dictionary/array) to a JSON format in NSData, which you can then save to persistent storage.
But, is there some reason you want to save your data as JSON rather than the myriad of native formats that Apple provides? JSON introduces a few limitations and requires an extra step to save it, so generally you wouldn't use it for local persistent storage. It's become a bit of a lingua franca (much as XML is) for communicating between between systems, but it wouldn't generally be one's first choice for local persistent storage.
There are a variety of different Cocoa Touch technologies designed for persistence.
See the relevant guide for each of the relevant technologies:
Preferences and Settings Programming Guide - You can use NSUserDefaults to save basic user preferences and settings
Property List Programming Guide - The most primitive and easy way to save arrays/dictionaries containing standard Cocoa objects (strings, numbers, etc.). E.g.
// to save dictionary to plist
[dictionary writeToFile:path atomically:YES];
or
// to load dictionary from plist
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:path];
Archives and Serializations Programming Guide - A variant on the property list approach, which allows you to modify your custom classes so that they can be archived (saved) with NSKeyedArchiver and unarchived (loaded) with NSKeyedUnarchiver.
Core Data Programming Guide - Apple's robust object persistence technology framework.
SQLite - See Ray Wenderlich tutorial or the SQLite.org site.
For more information, see the relevant guide.
Related
What is the use of plist in iOS? How can we implement the plist? Can any one please post some sample code for the plist because I am completely new to ios development.
Plist is a lightweight file that is often used to save some data in iOS and OSX applications. It is just a key-value pairs of readable data.
Only NSArray and NSDictionary objects can be written to plist files. Those can then contain NSString objects (and other objects, like NSDate and NSData, etc), but what you're asking for is not possible
Please read this Plist Guide.
Background:
I have an app that retrieves a list of restaurants from a database, each have an individual array of basic information about them (hours, name, address, etc). I would like to retrieve that information from the server on the apps first load, but then have it stored within the app itself, with either NSUserDefaults or Core Data, since the information is unlikely to change. The max number of restaurants I would be storing is about 25, is that a small enough data collection to use NSUserDefaults?
I have looked at similar questions with storing data with over 1,000 records, but I am only storing a small array.
Question:
NSUserDefaults is much easier to use than Core Data, so if possible I would like to avoid using Core Data. In my case, will there be a performance problem if I am storing my list of restaurants in NSUserDefaults instead of Core Data?
Depends on the
size
structure of data
requirements re integrity of the data
Just an Array of 10 or 20 "restaruants" I would certainly store in NSUserDefaults. But only when I am sure that this will never become more complex. Because when you later extend your model but started off with NSUserData then you may remain with NSUserDefaults just because you avoid migrating it to Core Data during the upgrade of an installed app.
So for more complex structures including references and when you have further plans with your app towards more functionality that may require more entities, then you should go for Core Data from start.
BTW, it is not that complicated as you may think.
However, instead of abusing NSUserDefaults, you could simply write an NSArray to file using -writeToFile:atomically: and -initWithContentsOfFile: to read them in.
NSUserDefaults is not intended for data, it's for storing simple key-value pairs like user settings and flags. Core Data is a bit hard to learn at first, but definitely worth it, even for simple applications.
If it really is a small, simple data set that won't change very often, you can also store some data in a local plist (i.e. save NSArray or NSDictionary to plist using writeToFile method). This isn't very different from using NSUserDefaults in terms of performance, although I think it's cleaner and easier to manage. If it never changes you can also include the plist with your app resources in XCode by creating a plist file and filling it in with your data.
Considering the amount of the data, user default or a specific plist/json file are all good. CoreData is definitely overkilling.
I need to store data that the user can add, they can add an unlimited amount. They can either be NSStrings or UIImages. I have looked into NSUserDefaults but it seems that it is used for small amounts of data such as settings or preferences.
What would be the best/most secure way to store the users information so that when they close the app it is still in the app. The data populates a UITableView and is a NSMutableArray.
Whats the best way to do this?
There must be a dozen ways to store user data in iOS. Here are several:
Property lists: An easy way to store a graph of common data storage objects and containers. This is a good place to start if you're just learning the iOS ropes.
NSKeyedArchiver and NSKeyedUnarchiver: Provides an easy way to serialize and deserialize your objects to/from a chunk of data, which you can then write/read using NSData's methods.
NSFileHandle: Read and write data in whatever format you like using a nice Objective-C API. More generally, you should read up on the iOS file system.
UIDocument: A full-featured starting point for managing user data, including syncing with iCloud.
Keychain: Not a general purpose data storage mechanism, but if you're storing sensitive items like passwords, credit card numbers, etc., you should use the keychain API.
POSIX file API: Good old C file handles with the read and write functions you learned in college, if you went to college before Java was a thing.
SQLite: According to the web site: "SQLite is the most widely deployed SQL database engine in the world."
Core Data: A powerful (but also somewhat complex object graph manager. This is a good choice if you have many different pieces of related data to store.
What would be the best/most secure way to store the users information
so that when they close the app it is still in the app. The data
populates a UITableView and is a NSMutableArray.
Best is subjective -- you'll need to consider your needs and look at the various options. For many people, though, best means least painful or easiest to learn. As mentioned above, property lists may be the way to go in that case. If your array contains simple data (strings, data, dates, numbers) in standard containers (arrays or dictionaries), your file I/O can be as simple as something like this:
// writing
[myArray writeToFile:somePath atomically:YES];
// reading
myArray = [[NSArray arrayWithContentsOfFile:somePath] mutableCopy];
You should use Core Data. There is a very good, free beginners course online avaibable called cs193p, see here http://www.stanford.edu/class/cs193p/cgi-bin/drupal/node/287, it is also available through iTunes U. It's really worth the time to watch and easy understandable.
If you have only some array you can check plist. is verry simple and powerful.
https://developer.apple.com/library/iOs/documentation/General/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html
This is a great resources: Should I use NSUserDefaults or a plist to store data?
What other ways than NSUserDefaults are there to save and get back Custom Objects? For me, NSUserDefaults has become too much of a hassle (it's not saving correctly), so I'm looking for another way to save data that will work. (I've already posted my problems, and I really just want to look for other ways to save data)
EDIT: I also need to be able to save things like UIIMages and UIButtons.
You can save data as normal text file or plist file.
You can use SQLLite to save data.
Other than this if you are using server driven application, then you can save your data on server and get back when you need that.
UIImages should be saved by creating a PNG or JPEG representation, then writing that NSData block out as you see fit. See UIImagePNGRepresentation.
UIButtons should be serialized/deserialized using the NSCoding protocol. Archives can take care of this for you.
NSData and UIButtons both support NSCoding, so I would recommend archiving instead of NSUserDefaults. See NSCoding for the beginning of that rabbit hole.
You cans use plist or coreData.As you used NSUserDefaults , that means data is quite small so plist will be a good idea.Both are apple's so quite effiecient .If data gets really large you can use sqlite.
To store custom objects, you need to make sure your custom objects implemented NSCoding protocol. Here is Apple's doc on NSCoding. . If you need a tutorial on how to implement NSCoding protocol, check out this site. To save UIImage to a file, you can convert the image to NSData and then using NSData's writeToFile method to write to a file. There are numerous examples on how to do the last part on SO. Here is one.
I'm building an iPhone app that is essentially a book, it will be bundled with a lot of text-heavy content.
I considered bundling the data as XML and load it when the application starts but the XML would contain a lot of nested structures and be a bit of a pain to parse.
Would it be better to use a plist? I'm concerned about memory usage and plists are loaded entirely into memory - can they be parsed in chunks? Is there a maximum size to a plist and how efficient are they?
I'm not sure how big the bundled content is going to be yet but I should imagine it could be anywhere from 500k to 4MB.
Property Lists are the native serialization format for anything derived from NSObject. There are some issues with mutable-state preservation, but overall plist is the format preferred by Apple.There are parsing methods available with NSData that abstract away the details of the mark-up. As for XML, you're burdened with the task of writing your own parser.
You can refer to this for further details.
It should be noted that a plist file itself is strict XML; in choosing plist, on the server-side you should be able to parse the plist XML and treat every two nodes as key-value pairs.
In my experience, plist is far easier for you to maintain and better in the long run. I have a similar situation and wrote an app that generates the data file my app reads using all of the same APIs with no extra setup. Its hitting the ground running (as long as you're familiar with Cocoa.)
Its even human readable with the property List Editor app included in the iPhone SDK. Although I don't recommend it for very large data structures by hand, that's why I mentioned how I built another app for that — the code generating the data and using it almost has a 1:1 comparison, they're that similar.
The plist editor does come in very handy to tweak an item or edit small-medium data and, once again, it hides the underlying XML.
If human-readability is a design goal, you should consider JSON. It's not the right answer for every application, but it bears considering. The open-source json-framework (here: http://code.google.com/p/json-framework/) is GREAT, and provides very convenient methods for encoding and decoding JSON strings to objects, as a category on NSString. So you can say:
NSString *jsonString = ...// however you're loading the goods
NSDictionary *myData = [jsonString JSONValue];
...and boom, you're working with native objects. For my money, that's even easier than reading a plist.
Why not ship the content as HTML? (Maybe split into chapters or some such)
That way you could immediately display it through a WebView without any parsing or reformatting.