Reputation: 1425
I've searched through the posts about static variables in Objective-C but haven't quite found an answer to this question:
In Java, I can create a class with static variables of the same class type, like this:
public class Status {
public static final Status SUCCESS = new Status(0, "Success");
public static final Status FAILURE = new Status(-1, "It's Broke");
private int number;
private String message;
private Status(int number, String message) {
this.number = number;
this.message = message;
}
}
And then I can use the static variables in Status like this:
public Status foo() {
...
return Status.FAILURE;
}
Could someone tell me how I would do something similar in Objective-C?
Upvotes: 0
Views: 328
Reputation: 40201
Most of the Cocoa APIs use simple enums to return such results.
typedef enum {
MyClassResultSuccess = 0,
MyClassResultFailure = -1
} MyClassResult;
If you want to use a more similar approach to what you posted, you could use class methods:
@interface Status
@property (nonatomic) int value;
@property (nonatomic, copy) NSString *message;
- (id)initWithValue:(int)value message:(NSString *)message;
+ (Status *)success;
+ (Status *)failure;
@end
@implementation Status
static Status *_success = nil;
static Status *_failure = nil;
- (id)initWithValue:(int)value message:(NSString *)message {
self = [super init];
if (self) {
self.value = value;
self.message = message;
}
return self;
}
+ (Status *)success {
if (!_success)
_success = [[Status alloc] initWithValue:0 message:@"Success"];
return _success;
}
+ (Status *)failure {
if (!_failure)
_failure = [[Status alloc] initWithValue:-1 message:@"Failure"];
return _failure;
}
@end
Upvotes: 1