What's the Objective-C approach to creating a matrix and storing it to a file?
Objective-C/iPhone beginner here...looking for a shove in the right direction.
I need to create an array that will later be stored using CoreData. In reality this is best described as an n x m matrix. Each row being a record. All data is integer.
something like this:
struct record
{
int index;
int mode;
int counter;
};
struct record database[20];
I am paraphrasing here. This isn't a database application. The matrix in question holds the data开发者_开发百科 necessary to run a state machine. But, you get the idea. A bunch of rows of integers.
What's the best O-C approach to this, considering that I need to save the matrix to the file system.
Can I use an NSArray of structs? (I don't think NSArray likes non-object types).
NSArray of NSArray's?
NSArray of NSDictionary?
Thank you,
-Martin
Personally I would create a 2D array, i.e. a NSArray of NSArrays with ints inside them. I'm assuming your data isn't actually just integers, but they are custom objects... In this case simply make your NSObjects conform to the NSCoding protocol and write some serialization code (2 methods, very simple stuff, one to pack the object, one to unpack the object) and then the entire matrix (object graph), can be saved and loaded very easily.
Here's a sample encode method taken from the Apple docs:
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:mapName forKey:@"MVMapName"];
[coder encodeFloat:magnification forKey:@"MVMagnification"];
[coder encodeObject:legendView forKey:@"MVLegend"];
[coder encodeConditionalObject:auxiliaryView forKey:@"MVAuxView"];
}
the decode method is very similar. They both allow you to modify and inspect the data before it is saved/after it is loaded if you need to do so.
This page has the info you need: http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Archiving/Articles/codingobjects.html%23//apple_ref/doc/uid/20000948-BCIHBJDE
Although the docs are often hard to learn from so here's another good resource: http://www.raywenderlich.com/1914/how-to-save-your-app-data-with-nscoding-and-nsfilemanager
Good luck, feel free to ask if anything isn't clear.
You are correct. NSArray only accepts objects that inherit from NSObject. Because of this, you can use an array of NSArrays, or convert your struct to an object that inherits from NSObject and store that in the array instead. The bonus for this is that you (may?) be able to use an NSManagedObject which you could then integrate nicely with core data.
Bear in mind that Core Data is an object graph, not a database. Because of this, you may want to start from that side, instead of designing your objects then trying to fit them into a relational database.
精彩评论