将枚举转换为类层次结构 [英] Converting enum into a class hierarchy
问题描述
枚举
{
MyConnectionStatusDisconnected = 0 ,
MyConnectionStatusConnecting,
MyConnectionStatusConnected,
MyConnectionStatusCount
};
typedef NSUInteger MyConnectionStatus;
我可能会像我这样在我的代理类中存在:
@interface ServerProxy:NSObject
{
MyConnectionStatus connectionStatus;
}
没关系,但是如果我想找出一个用户可读的解释的连接状态?我可能会有这样的静态函数:
+(NSString *)statusStringForInt:(MyConnectionStatus)status;
在这一点上,我很快就离开了面向对象编程的领域。
将此枚举重构为类层次结构的最佳方式是什么?
我不会将其重构为类层次结构。而是使用NSString常量:
// foo.h
extern NSString * MyConnectionStatusDisconnected;
// foo.m
MyConnectionStatusDisconnected = @连接状态:已断开连接;
isEqualToString:
将指针相等作为第一个测试,这样会很快。
然后可以使用您的字符串文件中的连接状态:断开连接
如果您需要本地化。
Let's say I am writing a class in Cocoa to act as a proxy to a server. To represent the current state of the connection, consider the enumeration:
enum
{
MyConnectionStatusDisconnected = 0,
MyConnectionStatusConnecting,
MyConnectionStatusConnected,
MyConnectionStatusCount
};
typedef NSUInteger MyConnectionStatus;
I may have it live in my proxy class like so:
@interface ServerProxy : NSObject
{
MyConnectionStatus connectionStatus;
}
That's fine, but what if I want to figure out a user-readable interpretation of the connection status? I might have a static function like this:
+(NSString*)statusStringForInt:(MyConnectionStatus)status;
At this point I'm quickly leaving the realm of object-oriented programming.
What would be the best way to refactor this enum into a class hierarchy?
I wouldn't refactor it into a class hierarchy. Instead, use NSString constants:
// foo.h
extern NSString *MyConnectionStatusDisconnected;
// foo.m
MyConnectionStatusDisconnected = @"Connection Status: Disconnected";
isEqualToString:
does pointer equality as the first test so this will be fast.
You can then use Connection Status: Disconnected
in your strings file(s) if you need to localize.
这篇关于将枚举转换为类层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!