How do I return an object similar to std :: pair in Objective-C?
I am coming from C ++ and I am trying to create a validation class for custom inputs in text fields. My function should return a bool
message as well (if the bool
message is YES NULL
). Does Objective-C have something similar to std::pair
from C ++ (which contains a couple of values)?
source to share
Cocoa doesn't std::pair
; you can create your own. However, a more idiomatic approach to the problem is similar to other methods that return errors, namely passing a pointer to a pointer to the error and returning BOOL
:
-(BOOL) validateInput:(id)input error:(NSError**)errPtr {
// Validate the input
// If the input is valid, do not assign `errPtr`, and return `YES`
// Otherwise, create a `NSError` object, and assign to errPtr
}
You can call this method like this:
NSError *err;
if (![validator validateInput:@"some input" error:&err]) {
// Show the error
}
For an example of how this idiom is used in Cocoa, see regularExpressionWithPattern:options:error:
class method NSRegularExpression
.
source to share
Well, not quite a couple, but you have several options:
One. Use an array or dictionary ("standard collection classes"):
NSArray *pair1 = @[@NO, @"Foo"];
NSArray *pair2 = @[@YES, [NSNull null]];
or
NSDictionary *pair = @{@"Flag" : @NO, @"Message" : @"Foo" };
so you understand ...
Two: why not write your own Pair class if it doesn't already exist?
@interface MyPair: NSObject
@property (assign) BOOL flag;
@property (strong) NSString *message;
@end
Why not try using Objective-C ++? Just list your source file with a .mm extension and then you can mix C ++ with objective-c. You cannot mix classes, but you can use standard template material. So in some Foo object I have a doFoo method with this code:
std::pair<id, NSString*> foo;
foo.first = @"First";
foo.second = @"second";
NSLog(@"%@ %@", foo.first, foo.second);
source to share