Archive Foundation framework

First, the list of attributes using XML archive

  This method is suitable for NSString, NSDictionary, NSarray, NSDate, NSnumber, which atomically parameter represents the first written dictionary temporary backup files, after successful, the final data is written to the specified file dic

. 1  #import <Foundation / Foundation.h>
 2  
. 3  int main ( int argc, const  char * the argv [])
 . 4  {
 . 5  
. 6      @autoreleasepool {
 . 7          // generate dic dictionary, and the dictionary file dic write xml file myFirstDic 
8          * dic = @ {NSDictionary @ " wukong " : @ " SO Smart " , @ " ranHanLu " : @ " SO Beautiful " , @ " Family " : @ " Best importtant!"};
 9         if ([dic writeToFile: @"myFirstDic" atomically:YES] == NO) {
10             NSLog(@"Write to file failed");
11         }
12         
13         //读取
14         dic = [NSDictionary dictionaryWithContentsOfFile: @"myFirstDic"];
15         for (NSString *key in dic) {
16             NSLog(@"key is: %@, value is : %@", key, dic[key]);
17         }
18     }
19     return 0;
20 }

Second, the application class NSKeyedUnarchiver obtained archiveRootObject: store the dictionary method

  This method can be used directly to NSString, NSDictionary, NSarray, NSDate, NSnumber archiving, to apply to all objects, and the need to rewrite encodeWithCoder initWithCoder method, see three

. 1  #import <Foundation / Foundation.h>
 2  
. 3  int main ( int argc, const  char * the argv [])
 . 4  {
 . 5  
. 6      @autoreleasepool {
 . 7          // applicable NSKeyedUnarchiver class obtained archiveRootObject: a method to store the dictionary 
. 8          
. 9          NSDictionary * DIC = @ {
 10                                @ " wukong " : @ " SO Smart " , @ " ranHanLu " : @ " SO Beautiful " , @ " Archive ": @"ending...."
11                               };
12         [NSKeyedArchiver archiveRootObject: dic toFile: @"dic.archive"];
13         
14         //读取
15         NSDictionary *new;
16         new = [NSKeyedUnarchiver unarchiveObjectWithFile: @"dic.archive"];
17         for (NSString *key in new) {
18             NSLog(@"key is: %@, value is : %@", key, new[key]);
19         }
20         
21     }
22     return 0;
23 }

 Third, the application class NSKeyedUnarchiver obtained archiveRootObject: The method of storing any object

  1. First protocol need to add custom object methods  . 1 #import <Foundation / Foundation.h>

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface testClass: NSObject
 4 
 5 @property (copy, nonatomic) NSString *name, *address;
 6 @end
 7 
 8 @implementation testClass
 9 //添加encodeWithCoder和initWithCoder方法
10 -(void) encodeWithCoder: (NSCoder *) encoder
11 {
12     [encoder encodeObject: name forKey: @"testClassName"];
13     [encoder encodeObject: address forKey: @"testClassAddress"];
14 }
15 
16 -(id) initWithCoder: (NSCoder *) decoder
17 {
18     name = [decoder decodeObjectForKey: @"testClassName"];
19     address = [decoder decodeObjectForKey: @"testClassAddress"];
20     
21     return self;
22 }
23 @synthesize name, address;
24 
25 @end
26 int main(int argc, const char * argv[])
27 {
28 
29     @autoreleasepool {
30         testClass *myTest = [[testClass alloc] init];
31         
32         myTest.name = @"wukong";
33         myTest.address = @"sichuan";
34         //归档
35         [NSKeyedArchiver archiveRootObject: myTest toFile: @"myTest.archive"];
36         //读出
37         myTest = [NSKeyedUnarchiver unarchiveObjectWithFile: @"myTest.archive"];
38         NSLog(@"Name is : %@, address is : %@", myTest.name, myTest.address);
39         
40     }
41     return 0;
42 }

 Fourth, the use NSData custom archive

  This example will be used to AddressBook, AddressCard, and myTest class.

  The following is the main program:

  

#import <Foundation/Foundation.h>
#import "AddressBook.h"
#import "AddressCard.h"
@interface testClass: NSObject

@property (copy, nonatomic) NSString *name, *address;
@end

@implementation testClass
@synthesize name, address;
//添加encodeWithCoder和initWithCoder方法
-(void) encodeWithCoder: (NSCoder *) encoder
{
    [encoder encodeObject: name forKey: @"testClassName"];
    [encoder encodeObject: address forKey: @"testClassAddress"];
}

-(id) initWithCoder: (NSCoder *) decoder
{
    name = [decoder decodeObjectForKey: @"testClassName"];
    address = [decoder decodeObjectForKey: @"testClassAddress"];
    
    return self;
}


@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        //创建myTest实例
        testClass *myTest = [[testClass alloc] init];
        // Create instance myBook 
        the AddressBook MyBook * = [[the AddressBook the alloc] the init];
         // Create instance myCard 
        AddressCard card1 * = [[AddressCard the alloc] the init];
         // Create NSMutableData instance, for storing archival data 
        NSMutableData mutableData * = [ data NSMutableData,];
         // create archive data for reading NSData 
        NSData * data = [NSData data];
         // Create NSKeyedArchiver instance, and to specify the archive mutableData 
        NSKeyedArchiver Archiver * = [[NSKeyedArchiver the alloc] initForWritingWithMutableData: mutableData];
         // Creating NSKeyedUnarchiver, for reading archive data 
        NSKeyedUnarchiver * Unarchiver;
        
        myTest.name = @"wukong";
        myTest.address = @"sichuan";
        [card1 setFirstName: @"sun" setLastName:@"wukong" setEmail:@"[email protected]" setAddress: @"huaGuoShan" setPhoneNumber: @"9999999"];
        [mybook addAddressCard: card1];
        //存档对象
        [archiver encodeObject: myTest forKey: @"MyTest"];
        [Archiver encodeObject: mybook forKey: @ " MyBook " ];
         // show archive end 
        [Archiver finishEncoding];
         // archive data written to the specified file 
        IF ([mutableData writeToFile: @ " firstDataArchive " atomically: YES] == NO) { 
            NSLog ( @ " \ nArchive the Failed " ); 
        } 
        
        // read the data from the archive specified file 
        data = [NSData dataWithContentsOfFile: @ " firstDataArchive " ];
         // specified decodes the data area 
        unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: data];
        
        //解码开始
        myTest = [unArchiver decodeObjectForKey: @"MyTest"];
        mybook = [unArchiver decodeObjectForKey: @"MyBook"];
        //显示
        [mybook list];
    }
    return 0;
}

 

  1.1 AddressCard类(interface)

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface AddressCard : NSObject
 4 @property (copy, nonatomic) NSString *firstName, *lastName, *email, *address, *phoneNumber;
 5 -(void) setName: (NSString *) theName;
 6 -(void) setEmail: (NSString *) theEmail;
 7 -(void) setFirstName: (NSString *) theFirstName setLastName: (NSString *) theLastName setEmail: (NSString *) theEmail setAddress: (NSString *) theAddress setPhoneNumber: (NSString *) thePhoneNumber;
 8 -(NSString *) name;
 9 -(NSString *) email;
10 -(void) print;
11 -(BOOL) isEqual: (AddressCard *) theCard;
12 -(NSComparisonResult) compareName: (AddressCard *) theCard;
13 -(NSComparisonResult) check: (AddressCard *) theCard;
14 @end

  1.2 AddressCard类 (implementation)

 1 #import "AddressCard.h"
 2 
 3 @implementation AddressCard
 4 
 5 @synthesize firstName, lastName, email, phoneNumber, address;
 6 
 7 -(void) setFirstName: (NSString *) theFirstName setLastName: (NSString *)theLastName setEmail: (NSString *) theEmail setAddress: (NSString *) theAddress setPhoneNumber: (NSString *) thePhoneNumber
 8 {
 9     firstName = theFirstName;
10     lastName = theLastName;
11     email = theEmail;
12     address = theAddress;
13     phoneNumber = thePhoneNumber;
14 }
15 
16 
17 -(void) print
18 {
19     NSLog(@"\n%@ %@ %@ %@ %@",firstName, lastName, email, address, phoneNumber);
20 }
21 
22 -(BOOL) isEqual: (AddressCard *) theCard
23 {
24     if ([firstName isEqualToString: theCard.firstName] && [email isEqualToString: theCard.email] && [lastName isEqualToString: theCard.lastName]) {
25         return YES;
26     }else{
27         return NO;
28     }
29 }
30 
31 -(NSComparisonResult) compareName: (AddressCard *) theCard
32 {
33     //return [name compare: theCard.name];
34     return [theCard.firstName compare: firstName];
35 }
36 
37 -(NSComparisonResult) check: (AddressCard *) theCard
38 {
39     return [theCard.lastName compare: lastName];
40 }
41 
42 -(void) encodeWithCoder: (NSCoder *) encoder
43 {
44     [encoder encodeObject: firstName forKey: @"addressCardFirstname"];
45     [encoder encodeObject: lastName forKey: @"addressCardLastname"];
46     [encoder encodeObject: email forKey: @"addressCardEmail"];
47     [encoder encodeObject: phoneNumber forKey: @"addressCardPhoneNumber"];
48 
49 }
50 
51 -(id) initWithCoder: (NSCoder *) decoder
52 {
53     firstName = [decoder decodeObjectForKey:@"addressCardFirstname"];
54     lastName = [decoder decodeObjectForKey:@"addressCardLastname"];
55     email = [decoder decodeObjectForKey:@"addressCardEmail"];
56     phoneNumber = [decoder decodeObjectForKey:@"addressCardPhoneNumber"];
57     return self;
58 }
59 @end

  2.1 AddressBook class (interface class)

 1 #import <Foundation/Foundation.h>
 2 #import "AddressCard.h"
 3 @interface AddressBook : NSObject
 4 @property (copy, nonatomic) NSString *bookName;
 5 @property (nonatomic, strong) NSMutableArray *book;
 6 
 7 -(instancetype) initWithName: (NSString *) name;
 8 -(void) addAddressCard: (AddressCard *) theCard;
 9 -(int) entries;
10 -(void) list;
11 -(AddressCard *) lookUp: (NSString *) name;
12 -(NSMutableArray *) lookUpAll: (NSString *) name;
13 -(void) removeCard: (AddressCard *) theCard;
14 -(void) sortByName;
15 -(NSArray *) sortBySelector;
16 -(BOOL) removeByLastName: (NSString *) lastName;
17 @end

  2.2 AddressBook类 (implementation)

#import "AddressBook.h"

@implementation AddressBook
@synthesize book, bookName;
-(instancetype) initWithName: (NSString *) name
{
    self = [super init];
    if (self) {
        bookName = [NSString stringWithString: name];
        book = [NSMutableArray array];
    }
    return  self;
}

-(instancetype) init{
    return [self initWithName: @"noName"];
}

-(void) addAddressCard: (AddressCard *) theCard
{
    [book addObject: theCard];
}

-(int) entries
{
    return (int)[book count];
}

-(void) list
{
    for (AddressCard *theCard in book) {
        [theCard print];
    }
}

-(AddressCard *) lookUp: (NSString *) name
{
    NSUInteger result = [book indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        if ([[obj firstName] caseInsensitiveCompare: name] || [[obj lastName] caseInsensitiveCompare: name] || [[obj email] caseInsensitiveCompare:name]  || [[obj phoneNumber] caseInsensitiveCompare: name]) {
            *stop = YES;
            return YES;
        }else{
            return NO;
        }
    }];
    if (result != NSNotFound) {
        return book[result];
    }else{
        return nil;
    }
    /*NSUInteger result =  [book indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        IF ([[obj name] caseInsensitiveCompare: name] == NSOrderedSame) { 
            *stop = YES;
            return YES; 
        } the else { 
            return NO; 
        } 
    }]; 
    IF (Result = NSNotFound!) { 
        return Book [Result]; 
    } the else { 
        return nil; 
    } 
     * / 
    / * 
    for (* theCard in AddressCard Book) { 
        IF ([theCard.name caseInsensitiveCompare: name] == NSOrderedSame) { 
            return theCard; 
        } 
    } 
    return Nil; 
     * / 
} 

// Check to obtain all of the elements in the array, and let Back to the variable array 
- (NSMutableArray *) lookupAll: (NSString * ) name 
{
     
    NSMutableArray * matchs = [NSMutableArray Array];
    NSIndexSet *all = [book indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        if ([[obj name] rangeOfString: name].location == NSNotFound) {
            [matchs addObject: obj];
            return YES;
        }else{
            return NO;
        }
    }];
    
    if ([matchs count]) {
        return matchs;
    }else{
        return  nil;
    }
    
    /*
    NSMutableArray *matchs = [NSMutableArray array];
    NSIndexSet *all = [book indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
       if ([[obj name] compare: name] == NSOrderedSame) {
           [matchs addObject: obj];
           return YES;
       }else{
           return  NO;
       }
   }];
    
    if ([matchs count]) {
        return matchs;
    }else{
        return nil;
    }
     */
}

-(void) removeCard: (AddressCard *) theCard
{
    [book removeObjectIdenticalTo: theCard];
    
}

-(void) sortByName
{
//    SEL s = @selector(compareName:);
//    [book sortUsingSelector: s];
    [book sortUsingComparator:^(id obj1, id obj2) {
        return [[obj2 name] compare:  [obj1 name]];
    }];
}

-(NSArray *) sortBySelector
{
    return [book sortedArrayUsingSelector: @selector(check:)];
}

-(BOOL) removeByLastName: (NSString *) lastName
{
    NSUInteger result = [book indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        if ([[obj lastName] caseInsensitiveCompare: lastName] == NSOrderedSame) {
            [book removeObject: obj];
            *stop = YES;
            return YES;
        }else{
            return NO;
        }
    }];
    if (result != NSNotFound) {
        return YES;
    }else{
        return NO;
    }
}

-(void) encodeWithCoder: (NSCoder *) encoder
{
    [encoder encodeObject: book forKey: @"AddressBookBook"];
    [encoder encodeObject: bookName forKey: @"AddressBookName"];
}

-(id) initWithCoder: (NSCoder *) decoder
{
    book = [decoder decodeObjectForKey: @"AddressBookBook"];
    bookName = [decoder decodeObjectForKey: @"AddressBookName"];
    return self;
}
@end

  

 

Reproduced in: https: //www.cnblogs.com/pretty-guy/p/3958366.html

Guess you like

Origin blog.csdn.net/weixin_33860528/article/details/93438707