开发者

creating new files in iphone sdk

How ca开发者_开发技巧n I create new files using iPhone SDK? I would like to provide the file name and its extension.


In Xcode:

  1. File >> New File...
  2. Mac OSX >> Other >> Empty File
  3. 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...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜