When I'm implementing NSCoding protocol in Objective-C, I'd like to use NSStringFromSelector(@selector(name))
to get the key path of a property, like below
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.accountName forKey:NSStringFromSelector(@selector(accountName))];
[aCoder encodeObject:self.userId forKey:NSStringFromSelector(@selector(userId))];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
_accountName = [aDecoder decodeObjectForKey:forKey:NSStringFromSelector(@selector(accountName))];
_userId = [aDecoder decodeObjectForKey:forKey:NSStringFromSelector(@selector(userId))];
}
return self;
}
I like this way because it prevents from mistyping without the need to define lots of string constants, and I will get warnings if I renamed those properties. But I couldn't find a way to do this in Swift, any ideas?