如何将 Objective C 对象实例编码为字符串?

How could I encode an Objective C object instance as a string?

我知道在 objective-c 中有多种归档对象的方法,但是有什么方法可以用来将 Objective-C 中的对象转换为可以存储在 txt 中的字符串文件(以及其他数据),然后从文件中提取以再次有效地重新创建相同的对象实例?

提前致谢

不建议这样做。

为什么不将对象保存到 NSDefaults 中并在需要时从那里提取 if?非常简单高效。

这是一个例子。 假设您有一个定义如下的用户对象

User.h

@interface User : NSObject

@property (nonatomic, strong) NSNumber *id;
@property (nonatomic, strong) NSString *first_name;
@property (nonatomic, strong) NSString *last_name;

@end

User.m

#import "User.h"

@implementation User

-(void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:id forKey:@"id"];
    [encoder encodeObject:first_name forKey:@"first_name"];
    [encoder encodeObject:last_name forKey:@"last_name"];
}

-(id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.id = [decoder decodeObjectForKey:@"id"];
        self.first_name = [decoder decodeObjectForKey:@"first_name"];
        self.last_name = [decoder decodeObjectForKey:@"last_name"];
    }
}

- (id)initWith:(User *)obj {
    if (self = [super init]) {
        self.id = obj.id;
        self.first_name = obj.first_name;
        self.last_name = obj.last_name;
    }
}

@end

每当你想保存对象时,你都可以做类似的事情

//Save the user object
User *user = [[User alloc] init];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:data forKey:@"YOUR_KEY"];
[defaults synchronize];

//Get the user object
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"YOUR_KEY"];
User *user = [[User alloc] initWith:[NSKeyedUnarchiver unarchiveObjectWithData:data]];