How ca开发者_开发技巧n I create new files using iPhone SDK? I would like to provide the file name and its extension.
In Xcode:
- File >> New File...
- Mac OSX >> Other >> Empty File
- Name it anything you want.
At Runtime:
[[NSFileManager defaultManager] createFileAtPath: <(NSString*)path>
contents: <(NSData*)contents>
attributes: <(NSDictionary*)attributes>];
I assume you want to save a custom object to a file within your application.
First, generate the path that you'll save your file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *docPath = [documentsPath stringByAppendingPathComponent:@"myFileName.ext"];
Save with:
[NSKeyedArchiver archiveRootObject:myObject toFile:docPath];
Retrieve with:
myObject = [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];
Finally - your object has to implement the NSCoding protocol with the two functions that I list below.
@interface MyObject : NSObject <NSCoding> {
//other functions, variables, etc..
- (void) encodeWithCoder: (NSCoder *)coder;
- (id) initWithCoder: (NSCoder *)coder;
}
Those functions inform iOS how to treat each one of your instance variables when it comes to retrieving or saving your object. See more here.
Good luck!
Are you trying to create files on the file system of the iOS device?
In that case you might want to take a look at NSFileHandle
and similar methods. Hard to say what would be the best to use in your case, since your question hardly reveals any details about what you want to achieve...
精彩评论