problem writing a NSMutableArray to file in cocoa - cocoa

A real beginners question.
I have a NSView subclass in which I create a NSMutableArray containing NSValues. When I want to write the array to a file using writetofile:atomatically: the file is created but it contains none of the NSValues that the mutable array does contain.
Does anyone know how I successfully can write this mutable array to a file?
Thanks

NSValues can't be saved in a plist (which is what writeToFile:atomically: does). Take a look here for the values you can save. (NSNumber is a kind of NSValue you can save, but other NSValues will fail.)
If you want to save your array with NSValues, you can use archiving instead of writeToFile:atomically:. NSArray and NSValue both support archiving, so you just convert the array to an archive and save that data to a file. (It will include the NSValues as well.) The code looks something like this:
[NSKeyedArchiver archiveRootObject:myArray toFile:#"myPath"];
To load it, just use:
NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:#"myPath"];

Related

How to add a double from a text field to a NSMutableArray xcode

Thanks To all that helped problem solved. :)
For some reason this wont work for me please help
array = [[NSMutableArray alloc] init];
inputted = [input.text doubleValue];
[array addObject:[NSNumber numberWithDouble:inputted]];
NSLog(#"%i",array.count);
where array is a NSMutableArray, inputted is a double and input is a text field
All that happens is that one saves but deletes the last one entered. how do i make it so that it saves everything entered?
You're always re-creating and re-initializing the "array" mutable array each time you go through your function so it's no wonder you are getting a result of "1" (one object in the array).
If you initialize your array once and only once, and move it out and away from the rest of that code (i.e. into a different function or whatever), then you will add additional objects to your mutable array and you'll see the count increment each time you add an object to your mutable array.
Makes sense?

Is the NSData a substring of the another NSData?

I have two NSData objects
NSData *toScan = /* initialized somehow with "Hello, this world." */;
NSData *toMatch = /* initialized somehow with "this" */;
What is the best way to know the toMatch bytes are the subset of toScan bytes?
I use C-functions for this purposes at this point: something like this
strstr([[toScan identifier] bytes], [[toMatch identifier] bytes]);
// returned bytes are null-terminated
but I think there is not the best way to use C-functions in object-oriented environment...
As of Snow Leopard and iOS 4.0, NSData has -rangeOfData:options:range: which should do what you want.
It's also pretty darn fast.
In a different question, I wrote an answer containing an NSData category with a rangeOfData: method:
Elegant Algorithm for Parsing Data Stream Into Record
That'll do what you're looking for.

I have a plist that is an array of dictionaries I need to save to documents directory is this code correct?

Is the code below correct for saving to disk?
// get the path to the "Documents" directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// get the path to our plist ("Documents/foo.plist")
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"foo.plist"];
// read or create plist
NSMutableDictionary *dict;
// check if our plist already exists in the Documents directory...
NSFileManager *fileManager = [NSFileManager defaultManager];
if ( [fileManager fileExistsAtPath:plistPath] ) {
// ...if it does, read it
NSLog(#"dict existed, reading %#", plistPath);
dict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
} else {
// ...if it doesn't, create it
NSLog(#"dict didn't exist, creating...");
dict = [NSMutableDictionary dictionaryWithCapacity:1];
No.
For one thing, it's missing a closing brace at the end, but maybe you just left that out when copying the code into the question.
For another, the code reads in a dictionary; it does not get an array (of anything) from anywhere, nor does it write anything (array or anything else) out.
It sounds like you copied the code from somewhere, hoping that it's what you need. Don't do that. Write your own code. Read code if you want, but only read it; do not just copy code into your program without understanding what it does, and don't rely on other people to tell you what code does.
In order to be a programmer in any language or framework, you must be able to read code in that language/framework. Read the Objective-C Programming Language and read the Cocoa Fundamentals Guide; once you know the concepts those guides teach, all that remains is to practice reading code.
You must also, obviously, be able to write code in the target language/framework. Copying other people's code is not a substitute. At best, you will end up with a shoddy program that is flaky or just doesn't work; at worst (if you're “programming” as a contractor or employee), you will be guilty of plagiarism.

Cannot Archive Array of Values Representing CGPoints

I have converted CGPoint To NSValue and put all the resulting values in q NSArray but when I use [NSKeyedArchiver archiveRootObject:ArrayName toFile:PointArrayFile]; it gives me error.
So what's the problem?
You don't say what problem you're seeing but in general you're probably better off using NSStringFromCGPoint and CFPointFromString to store and retrieve the points.

Cocoa: Element count of property list without building dictionary?

What is the best way to count the number of entries in a property list?
I currently build a dictionary from the plist entries (*) and then use the dictionary's count:
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:myPlistPath];
NSDictionary *myPlistDict = (NSDictionary *) [NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
NSLog(#"There are %d entries in the plist.", [myPlistDict count]);
This strikes me as unnecessarily "heavy", but I was not able to find a more efficient solution. Any ideas?
(*) targeting 10.5 and therefore using the deprecated +propertyListFromData:… class method.
Well... if you're converting to XML anyway, you could use NSXMLNode's childCount method. The documentation does suggest that it's more efficient than calling [children count], but the creation of the NSXMLNode might make this just as bad (or even worse than) the NSDictionary method.
Have you profiled? Are you working with particularly large plists? Are you requesting this count often? I say: use NSDictionary, cache the value if you request it often, and move on unless this is unacceptably slow. (Yeah, it looks ugly right now, but there are bigger things to worry about.)

Resources