iOS Archiving/Unarchiving, 以及文件系統

應用的sandbox:  Documents Library tmp
沙盒的根目錄下有這3個可操作的文件夾.
獲得Document的path:
方法一:    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                 NSString *ourDocumentPath = [documentPaths objectAtIndex:0];
方法二:      

       NSString *sandboxPath = NSHomeDirectory();

       NSString *ourDocumentPath = [sandboxPath stringByAppendingPathComponent:@"Documents"];



都會的到這樣的結果:

/var/mobile/Applications/9EFD60C1-E627-4CCD-BA62-24ED952A0922/Documents




Archiving(固化)/Unarchiving(解固)

    NSString *sandboxPath = NSHomeDirectory();

    NSString *archivePath = [sandboxPath stringByAppendingPathComponent:@"Documents/archive.data"];

    

    Person *p = [[Person alloc] init];

    Body *b = [[Body alloc] init];

    b.hand  = @"my hand";

    p.body = b;

    [NSKeyedArchiver archiveRootObject:p toFile:archivePath];

    

    Person *up = [NSKeyedUnarchiver unarchiveObjectWithFile:archivePath];

    NSLog(@"%@", up.body.hand);


下面是需要的連個類: body ,person :

#import <Foundation/Foundation.h>

#import "Body.h"


@interface Person : NSObject <NSCoding


@property Body *body;



@end


#import "Person.h"


@interface Person ()

{

    NSInteger age;

}


@end


@implementation Person

@synthesize body;


- (void) encodeWithCoder:(NSCoder *)aCoder

{

    [aCoder encodeObject:body forKey:@"body"];

    [aCoder encodeInteger:age forKey:@"age"];

}


-(id) initWithCoder:(NSCoder *)aDecoder

{

    self = [super init];

    if (self) {

        self.body = [aDecoder decodeObjectForKey:@"body"];

    }

    return self;

}


@end


#import <Foundation/Foundation.h>


@interface Body : NSObject <NSCoding>


@property NSString *hand;


@end


#import "Body.h"


@implementation Body

@synthesize hand;


-(void) encodeWithCoder:(NSCoder *)aCoder

{

    [aCoder encodeObject:hand forKey:@"hand"];

}


-(id) initWithCoder:(NSCoder *) aDecoder

{

    self = [super init];

    if (self) {

        hand = [aDecoder decodeObjectForKey:@"hand"];

    }

    return self;

}


@end





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章