开发者

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];
开发者_如何学JAVA


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜