set ivars from NSDictionnary - objective-c

I'm currently working on a project where the user defines some parameters in a NSDictionnary, that I'm using to setup some objects.
For example, you can ask to create a Sound object with parameters param1=xxx, param2=yyy, gain=3.5 ... Then an Enemi object with parameters speed=10, active=YES, name=zzz ...
{
active = NO;
looping = YES;
soundList = "FINAL_PSS_imoverhere_all";
speed = 100.0;
}
I then instantiate my classes, and would like to set the ivars automatically from this dictionnary.
I've actually wrote some code to check that this parameter exists, but I'm having trouble in actually setting the parameter value, especially when the parameter is non object (float or bool).
Here's what I'm doing so far :
//aKey is the name of the ivar
for (NSString *aKey in [properties allKeys]){
//create the name of the setter function from the key (parameter -> setParameter)
NSString *setterName = [aKey stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[aKey substringToIndex:1] uppercaseString]];
setterName = [NSString stringWithFormat:#"set%#:",setterName];
SEL setterSelector = NSSelectorFromString(setterName);
//Check if the parameter exists
if ([pge_object respondsToSelector:setterSelector]){
//TODO : automatically set the parameter
}
else{
[[PSMessagesChecker sharedInstance]logMessage:[NSString stringWithFormat:#"Cannot find %# on %#", aKey, [dict objectForKey:#"type"]] inColor:#"red"];
NSLog(#"Cannot find %# on %#", aKey, [dict objectForKey:#"type"]);
}
}
}
As you can see, I don't know what to do once I've found that the parameter exists on the object. I tried to use "performSelector... withObject..., but my problem is that some of the parameters are non-objects (float or bool).
I also tried to get the class of the parameter, by using the setter, but it didn't help.
Did anyone manage to do something like that?

Jack Lawrence's comment is spot on.
What you are looking for is called Key Value Coding, or just KVC.
This fundamental part of Cocoa lets you get and set any instance variable using its name as a String and a new value.
It will automatically handle coercing Objects to primitive values, so you can use it for int and float properties too.
There is also support for validating values and handling unknown properties.
see the docs
your code, without validation, could be written
for( id eachKey in props ) {
[anOb setValue:props[eachKey] forKey:eachKey];
}
or just
[anOb setValuesForKeysWithDictionary:props];
as Jack said.

For the non-object parameters you have to put them into an object, for example NSNumber or NSValue. You can then add these objects into your dictionary.
For Example:
float f = 0.5;
NSNumber f_obj = [NSNumber numberWithFloat:f];

Related

How to create an inline conditional assignment in Objective-C?

My Pet class has 2 properties: BOOL isHungry and NSNumber *age.
I want to put the properties of Pet myPet into NSMutableDictionary *myMap.
This is my code is Java. I am trying to write an equivalent in Objective-C
myMap.put("isHungry", myPet == null ? null : myPet.isHungry);
myMap.put("age", myPet == null ? null : myPet.age);
This is my current Objective-C version:
[myMap addEntriesFromDictionary:#{
#"isHungry" : myPet ? myPet.isHungry : (NSInteger)[NSNull null],
#"age" : myPet ? myPet.age : [NSNull null],
}];
The error for the second line is the following:
Incompatible operand types ('int' and 'NSNull * _Nonnull')
The compiler stopped complaining about the first line when I added (NSInteger).
If I put the same on the second line, the error goes away, but the compiler complains about the first line again:
Collection element of type 'long' is not an Objective-C object
I am a noob in Obj-C and I am totally lost. I would also like to know the best practice for Obj-C.
Dictionaries in Objective C can only store objects, and only existing objects.
You turn a boolean or arithmetic value like myPet.isHungry into an NSNumber object by writing #(myPet.isHungry). You create an object that can stand in for nil by writing [NSNull null].
When you try to extract a value from a dictionary, you get an object or nil. You check if the object represents nil by checking
if (value == nil || value == [NSNull null])
The second comparison works because there is always ever only one NSNull object.
If you know that the value is an NSNumber object, you can use boolValue or integerValue etc. to extract the value.
Your isHungry is a BOOL. Arrays and dictionaries can store only objects. But BOOL and NSInteger are primitive types and not objects (that's why you get the error). But you can convert it to an object (NSNumber in this case) and add it to a dictionary.
You can convert BOOL value to NSNumber in two ways, by adding # in front of a value or by using numberWithBool:
Example:
NSNumber *isHungry = #(myPet.isHungry); // OR
NSNumber *isHungry = [NSNumber numberWithBool:myPet.isHungry];
You can do it inline so your code will look (and work) like:
[myMap addEntriesFromDictionary:#{
#"isHungry" : myPet ? #(myPet.isHungry) : [NSNull null],
#"age" : myPet ? myPet.age : [NSNull null],
}];
When you retrieve data from the dictionary you'll get an NSNumber you stored before. But you can convert it back to a BOOL if needed.
// getting BOOL back
NSNumber *isHungryObj = myMap[#"isHungry"]; // it must be NSNumber not NSNull!
BOOL isHungry = isHungry.boolValue;
But in the case above you have to be sure that your stored object is actually a NSNumber and not NSNull. Because in the case of NSNull the app will crash because NSNull is not NSNumber and doesn't respond to boolValue.
So to avoid that you'll either:
always have to check the returned object against NSNull (not the best solution, and storing two different types of objects under the same key in a dictionary is not the best practice)
depending on your needs it may be wiser to store instead of NSNull some default values in the case if there's no myPet. Like setting #NO for isHungry and #0 for age
or you can check the existence of myPet before adding values and if it doesn't exist then just don't add anything to myMap. In this case if you don't add anything to myMap, then calling myMap[#"isHungry"] will return nil.
It is another variant of null in Objective-C. It's easier to check for nil than NSNull and nothing bad will happen even if you send some message to nil. In Objective-C sending messages to nil is allowed. You can't store nil in a dictionary as you can do with NSNull, but you can compare objects to nil.
Sample code for the 3rd option:
// adding to a dictionary, does the same thing as your code
if (myPet != nil) // OR if (myPet)
{
myMap[#"isHungry"] = #(myPet.isHungry);
myMap[#"age"] = myPet.age;
}
// retrieving
if (myMap[#"age"])
{
// number exists, you can do something with it
}
And since nil can have messages sent to it without a problem, sometimes you don't even need to check for nil, for example in such case:
if ([myMap[#"age"] integerValue] == 5) // returns YES if it's 5 and NO in any other case even if #"age" wasn't set and is nil
Hope this helps.
As you have a class Pet with #property BOOL isHungry; and #property NSNumber *age; and your myMap is NSMutableDictionary your solution should look like..
Pet *myPet = [[Pet alloc] init];
myPet.age = #(2);
myPet.isHungry = YES;
NSMutableDictionary *myMap = [[NSMutableDictionary alloc] init];
if (myPet!=nil) {
[myMap addEntriesFromDictionary:#{
#"isHungry" : #(myPet.isHungry),
#"age" : myPet.age
}];
}
// with this you store only the values of Pet
NSLog(#"%#",myMap.description);
// but that goes even easier..
NSMutableDictionary *myDict = [NSMutableDictionary new];
myDict[#"Pet1"] = myPet;
NSLog(#"%#",myDict.description);
Pet *petInDict = myDict[#"Pet"];
NSLog(#"age=%# isHungry=%#",petInDict.age, (petInDict.isHungry ? #"YES":#"NO") );
// should be age=(null) isHungry=NO
// because we stored with key myDict[#"Pet1"] and not myDict[#"Pet"]
// ok lets take the key we used
Pet *pet1 = myDict[#"Pet1"];
NSLog(#"age=%# isHungry=%#",pet1.age, (pet1.isHungry ? #"YES":#"NO") );
As there are generic data types that are not subclasses of NSObject you cant store them in dictionarys without making them to objects.
#(yournumber) // converts to NSNumber
#(YES) // converts to NSNumber = 1
#(NO) // converts to NSNumber = 0
#[#(1),#(2),#(3)] // converts to an NSArray with 3 NSNumbers
#{} // this one you know allready, its a NSDictionary
#"hello" // well NSString of course
#selector(name:) // thats a pointer to a method with name:, of type SEL
...
#{#"key1":#YES, #"key2":#NO}
// it is possible to convert BOOL directly
you can also initiate this way, but you see it can become looking strange
NSMutableDictionary *syntaxsugar = [(#{#"isHungry":#(myPet.isHungry), #"age":myPet.age}) mutableCopy];
mutableCopy generates a mutable copy of the leading Datatype which is NSDictionary.

C: Double Pointers and Objective-C NSError Double Pointers Usage

I happened to stumble upon posts here on SO regarding the double star (**) usage with NSError. Decided to dig it a little deeper, which led me revisiting C.
I have already read many posts here (not a duplicate here) on NSError and I understand why they do so.
So, I decided to write a little snippet in the IDE (Xcode) to see it myself in action.
int a = 10;
int b = 20;
int *c = &a;
int *d = &b;
int **e = &d;
NSLog(#"Before: a is: %d b is: %d", a, b);
[self testSingleStar:c];
[self testDoubleStar:e];
NSLog(#"After: a is: %d b is: %d", a, b);
Methods:
- (void)testDoubleStar:(int**)x
{
int anotherValue1 = 22;
**x = anotherValue1;
}
- (void)testSingleStar:(int*)x
{
int anotherValue2 = 33;
*x = anotherValue2;
}
Output:
Before: a is: 10 b is: 20
After: a is: 33 b is: 22
Both values of a (via a single pointer) and b (via a double pointer) did get changed.
So, if we can change the value (of a) using only a single pointer, why would we need to use a pointer to a pointer to NSError so that we could modify the NSError object in method call where NSError object is passed in its parameter (&error)?
In addition:
In regards to the above, passing something to the parameter in C is actually passing a copy to the parameter (even in the case of a single pointer only a copy of it will get passed), so anything change made within the scope of the method will not effect the original value passed to it (that's why they use a double star).
But the above sample, in which only a single pointer is used, seems to contradicts this because the value (namely a pointed to by a single pointer - c) did get changed?
You can modify an external variable of type foo by providing a foo * to a function or method:
+ (void)doJobReturningInt(int *) { ... }
int a;
[MyClass doJobReturningInt:&a]; // may modify the value of the variable a;
So far, so good.
Now how do we declare a variable storing an NSError object? With the NSError * type:
NSError *error;
So if we want to modify it, we need to provide a pointer to its type, that is to say NSError **.
+ (void)doJobReturningError:(NSError **)outError { ... }
NSError *error;
[MyClass doJobReturningError:&error]; // may modify the value of the variable error;
See? This is the same situation: for modifying the type foo, provide a foo*.
This is because you can't just have an NSError object... you can only deal with Objective-C objects by pointer... so while you could theoretically take a pointer to NSError and swap its contents... it would mess up encapsulation (other things could be relying on that data that used to be there.).
also just reassigning the pointer to a new value doesn't work, because it doesn't affect the callers version.
so while it seems tempting to:
-(void)method:(NSError *)errObject
{
//something like
errObject = [NSError errorWithBlah:#"blah"]; // this will only change the local variable errObject, not the callers version, that pointer is just copied by value.
}
or
/// not real code, didn't check to see if my params are in the correct places etc.
-(void)mangler:(NSError *)errObject
{
//something like
errObject = realloc(errObject,sizeof *errorObject);
memcpy(errObject,[NSError new],sizeof NSError);
// you have killed the old version that may be in use.
}

error with NSSring

I'm very new to objective-c and I'm getting a basic error and unsure on how to fix it.
for(ZBarSymbol *sym in syms) {
resultText.text = sym.data; //sym.data = 0012044012482
[self phpPost:(int)sym.data];
break;
}
}
- (void)phpPost: (int)barcode {
NSString *theValue = [NSString stringWithFormat:#"%#", barcode]; //problem line
labelScan.text = theValue;
//labelScan.text = #"Barcode scanned";
}
when i use #"%#" the text of the label is correct (0012044012482), but when i use #"%d" it isn't (random number every time i restart the app). I would like to use #"%#" (or something that works) but for some reason xCode is giving me an error. and I'm unsure on how to fix the error.
The error is:
Format specifies type 'id' but the argument has type 'int'
In the end I plan on having that code (sym.data) written to a MySQL database using the POST method.
You can't just convert it to an int by casting if it's an object (which it must be if the %# format specifier isn't causing a crash).
Assuming from the fact that you're assinging it directly to a label's text that it's an NSString, you should either change the parameter type of phpPost:
- (void)phpPost: (NSString *)barcode {
labelScan.text = barcode;
}
or extract the intValue before passing sym.data:
[self phpPost:[sym.data intValue]];
and then use the proper %d format specifier in phpPost:.
Your barcode isn't an int, it is an NSString. Instead of doing (int)sym.data, pass in [sym.data intValue]. That should correctly convert it to an integer.
The reason you get a random number is because you can't just cast a string object to a primitive data type :)
I don't know what type sym.data is, but it is likely a pointer to an object, and not the value itself. You cast that pointer to int, so when you are using %d you are effectively printing the memory location of the object. That is why it changes each time you run the program (Objective-C let's you do this without any warnings - something to watch out for).
To fix this, either extract the integer value you need from the sym.data object using it's properties; or pass the object as a pointer. For instance, you could try calling your method like this:
[self phpPost:sym.data];
And then change your method to be:
- (void)phpPost: (id)barcode {
NSString *theValue = [NSString stringWithFormat:#"%#", barcode];
labelScan.text = theValue;
}
Ok, I did some thinking while I was at work today, and I figured out that an INT isn't going to work for me. if I make that object to an int, I would loss some data that is vital to what I'm doing. eg. object=001234 int=1234. I need the zeros. So, in the end, I'm keeping it an object (string) and just passing it into the function.
Here is my code after I got it working correctly.
for(ZBarSymbol *sym in syms) {
resultText.text = sym.data;
[self phpPost:sym.data];
break;
}
}
- (void)phpPost: (NSString *)barcode {
labelScan.text = barcode;
//labelScan.text = #"Barcode scanned"; //My custon label
}
Thanks, everyone for your responses. Your answer will not go unused. I'm sure I'll be needing this information here soon.
O, if you see that I did this wrong, or not the correct way, please make a comment and tell me .

Objective-c: Dynamic Class Names

I'm not sure if I worded the subject correctly. I am looping through an array, within each loop I am trying to instantiate a class, but I want to dynamically create the name. Like so:
int i = 0;
for(NSString* thisdatarow in filedata) {
i++;
NSString* thisad = [NSString stringWithFormat:#"ad%d", i];
NSLog(#"%#", thisad);
AdData* thisad = [AdData new];
}
In the example above I want AdData* thisad... to be named dynamically - "ad1", "ad2", "ad3"...and so on. I get a conflicting type error.
This code also generated an error:
int i = 0;
for(NSString* thisdatarow in filedata) {
i++;
AdData* [NSString stringWithFormat:#"ad%d", i] = [AdData new];
}
Is there a way to do this?
You can't do that in Objective-C.
Use a NSString to AdData map--it'll do basically the same thing!
**edit: To clarify, use an:
NSMutableDictionary *dict;
with keys that are NSString* objects containing the ad names, and values that are the AdData* objects.
i.e.
[dict setValue:ad1 forKey:#"ad1"];
to set the values, and
[dict valueForKey:#"ad1"];
to get the values. (ignore the obvious memory leaks there with the strings...)
This isn't possible. While Objective-C is very dynamic, it's not that dynamic.
The suggested way to do this would be to create your instances and put them into an array, not assigning them to explicitly named variables.
You can then refer to them individually using their index in the array.
Something like this:
NSMutableArray *ads = [NSMutableArray array];
for(NSString* thisdatarow in filedata) {
AdData* thisad = [[[AdData alloc] init] autorelease];
[ads addObject:thisad];
}
// get third ad:
AdData *ad = [ads objectAtIndex:2];
Alternatively you could create an NSDictionary, if you really want to refer to them by a name, like this:
NSMutableDictionary *ads = [NSMutableDictionary dictionary];
int i = 0;
for(NSString* thisdatarow in filedata) {
i++;
AdData* thisad = [[[AdData alloc] init] autorelease];
NSString *keyName = [NSString stringWithFormat:#"ad%d", i];
[ads setObject:thisad forKey:keyName];
}
// get third ad
AdData *ad = [ads objectForKey:#"ad2"];
Cant be done Without using a C array, which would look like this:
AdData **ad = malloc(sizeof(AdData) * numberOfAds);
ad[1] = [AdData new];
// etc.
if (ad)
free(ad);
But I don't know how that would work because of how Objective-C classes are stored....
Local variable names are a purely compile-time concept. So you cannot do anything "dynamic" (i.e. at runtime) with it. The compiler is free to rename the variables and add or remove variables as it sees fit.
If you think about it, what is the point of dynamically manipulating local variable names? In order to use the dynamically-named variable again, you must either 1) explicitly refer to the variable name, in which case you have hard-coded the name (not so dynamic), or 2) dynamically construct the name again. If it's (1), then there is only a fixed set of variable names, so dynamic-ness is unnecessary. If it's (2), you're missing the point of local variable names (the whole point of which is so they can be referred to explicitly).

Objective-C switch using objects?

I'm doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects properties from the result.
First version looked like this:
if([elementName compare:#"companyName"] == 0)
[character setCorporationName:currentElementText];
else if([elementName compare:#"corporationID"] == 0)
[character setCorporationID:currentElementText];
else if([elementName compare:#"name"] == 0)
...
But I don't like the if-else-if-else pattern this produces. Looking at the switch statement I see that i can only handle ints, chars etc and not objects... so is there a better implementation pattern I'm not aware of?
BTW I did actually come up with a better solution for setting the object's properties, but I want to know specifically about the if-else vs switch pattern in Objective-C
You should take advantage of Key-Value Coding:
[character setValue:currentElementText forKey:elementName];
If the data is untrusted, you might want to check that the key is valid:
if (![validKeysCollection containsObject:elementName])
// Exception or error
I hope you'll all forgive me for going out on a limb here, but I would like to address the more general question of parsing XML documents in Cocoa without the need of if-else statements. The question as originally stated assigns the current element text to an instance variable of the character object. As jmah pointed out, this can be solved using key-value coding. However, in a more complex XML document this might not be possible. Consider for example the following.
<xmlroot>
<corporationID>
<stockSymbol>EXAM</stockSymbol>
<uuid>31337</uuid>
</corporationID>
<companyName>Example Inc.</companyName>
</xmlroot>
There are multiple approaches to dealing with this. Off of the top of my head, I can think of two using NSXMLDocument. The first uses NSXMLElement. It is fairly straightforward and does not involve the if-else issue at all. You simply get the root element and go through its named elements one by one.
NSXMLElement* root = [xmlDocument rootElement];
// Assuming that we only have one of each element.
[character setCorperationName:[[[root elementsForName:#"companyName"] objectAtIndex:0] stringValue]];
NSXMLElement* corperationId = [root elementsForName:#"corporationID"];
[character setCorperationStockSymbol:[[[corperationId elementsForName:#"stockSymbol"] objectAtIndex:0] stringValue]];
[character setCorperationUUID:[[[corperationId elementsForName:#"uuid"] objectAtIndex:0] stringValue]];
The next one uses the more general NSXMLNode, walks through the tree, and directly uses the if-else structure.
// The first line is the same as the last example, because NSXMLElement inherits from NSXMLNode
NSXMLNode* aNode = [xmlDocument rootElement];
while(aNode = [aNode nextNode]){
if([[aNode name] isEqualToString:#"companyName"]){
[character setCorperationName:[aNode stringValue]];
}else if([[aNode name] isEqualToString:#"corporationID"]){
NSXMLNode* correctParent = aNode;
while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){
if([[aNode name] isEqualToString:#"stockSymbol"]){
[character setCorperationStockSymbol:[aNode stringValue]];
}else if([[aNode name] isEqualToString:#"uuid"]){
[character setCorperationUUID:[aNode stringValue]];
}
}
}
}
This is a good candidate for eliminating the if-else structure, but like the original problem, we can't simply use switch-case here. However, we can still eliminate if-else by using performSelector. The first step is to define the a method for each element.
- (NSNode*)parse_companyName:(NSNode*)aNode
{
[character setCorperationName:[aNode stringValue]];
return aNode;
}
- (NSNode*)parse_corporationID:(NSNode*)aNode
{
NSXMLNode* correctParent = aNode;
while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){
[self invokeMethodForNode:aNode prefix:#"parse_corporationID_"];
}
return [aNode previousNode];
}
- (NSNode*)parse_corporationID_stockSymbol:(NSNode*)aNode
{
[character setCorperationStockSymbol:[aNode stringValue]];
return aNode;
}
- (NSNode*)parse_corporationID_uuid:(NSNode*)aNode
{
[character setCorperationUUID:[aNode stringValue]];
return aNode;
}
The magic happens in the invokeMethodForNode:prefix: method. We generate the selector based on the name of the element, and perform that selector with aNode as the only parameter. Presto bango, we've eliminated the need for an if-else statement. Here's the code for that method.
- (NSNode*)invokeMethodForNode:(NSNode*)aNode prefix:(NSString*)aPrefix
{
NSNode* ret = nil;
NSString* methodName = [NSString stringWithFormat:#"%#%#:", prefix, [aNode name]];
SEL selector = NSSelectorFromString(methodName);
if([self respondsToSelector:selector])
ret = [self performSelector:selector withObject:aNode];
return ret;
}
Now, instead of our larger if-else statement (the one that differentiated between companyName and corporationID), we can simply write one line of code
NSXMLNode* aNode = [xmlDocument rootElement];
while(aNode = [aNode nextNode]){
aNode = [self invokeMethodForNode:aNode prefix:#"parse_"];
}
Now I apologize if I got any of this wrong, it's been a while since I've written anything with NSXMLDocument, it's late at night and I didn't actually test this code. So if you see anything wrong, please leave a comment or edit this answer.
However, I believe I have just shown how properly-named selectors can be used in Cocoa to completely eliminate if-else statements in cases like this. There are a few gotchas and corner cases. The performSelector: family of methods only takes 0, 1, or 2 argument methods whose arguments and return types are objects, so if the types of the arguments and return type are not objects, or if there are more than two arguments, then you would have to use an NSInvocation to invoke it. You have to make sure that the method names you generate aren't going to call other methods, especially if the target of the call is another object, and this particular method naming scheme won't work on elements with non-alphanumeric characters. You could get around that by escaping the XML element names in your method names somehow, or by building an NSDictionary using the method names as the keys and the selectors as the values. This can get pretty memory intensive and end up taking a longer time. performSelector dispatch like I described is pretty fast. For very large if-else statements, this method may even be faster than an if-else statement.
If you want to use as little code as possible, and your element names and setters are all named so that if elementName is #"foo" then setter is setFoo:, you could do something like:
SEL selector = NSSelectorFromString([NSString stringWithFormat:#"set%#:", [elementName capitalizedString]]);
[character performSelector:selector withObject:currentElementText];
or possibly even:
[character setValue:currentElementText forKey:elementName]; // KVC-style
Though these will of course be a bit slower than using a bunch of if statements.
[Edit: The second option was already mentioned by someone; oops!]
Dare I suggest using a macro?
#define TEST( _name, _method ) \
if ([elementName isEqualToString:# _name] ) \
[character _method:currentElementText]; else
#define ENDTEST { /* empty */ }
TEST( "companyName", setCorporationName )
TEST( "setCorporationID", setCorporationID )
TEST( "name", setName )
:
:
ENDTEST
One way I've done this with NSStrings is by using an NSDictionary and enums. It may not be the most elegant, but I think it makes the code a little more readable. The following pseudocode is extracted from one of my projects:
typedef enum { UNKNOWNRESIDUE, DEOXYADENINE, DEOXYCYTOSINE, DEOXYGUANINE, DEOXYTHYMINE } SLSResidueType;
static NSDictionary *pdbResidueLookupTable;
...
if (pdbResidueLookupTable == nil)
{
pdbResidueLookupTable = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithInteger:DEOXYADENINE], #"DA",
[NSNumber numberWithInteger:DEOXYCYTOSINE], #"DC",
[NSNumber numberWithInteger:DEOXYGUANINE], #"DG",
[NSNumber numberWithInteger:DEOXYTHYMINE], #"DT",
nil];
}
SLSResidueType residueIdentifier = [[pdbResidueLookupTable objectForKey:residueType] intValue];
switch (residueIdentifier)
{
case DEOXYADENINE: do something; break;
case DEOXYCYTOSINE: do something; break;
case DEOXYGUANINE: do something; break;
case DEOXYTHYMINE: do something; break;
}
The if-else implementation you have is the right way to do this, since switch won't work with objects. Apart from maybe being a bit harder to read (which is subjective), there is no real downside in using if-else statements this way.
Although there's not necessarily a better way to do something like that for one time use, why use "compare" when you can use "isEqualToString"? That would seem to be more performant since the comparison would halt at the first non-matching character, rather than going through the whole thing to calculate a valid comparison result (though come to think of it the comparison might be clear at the same point) - also though it would look a little cleaner because that call returns a BOOL.
if([elementName isEqualToString:#"companyName"] )
[character setCorporationName:currentElementText];
else if([elementName isEqualToString:#"corporationID"] )
[character setCorporationID:currentElementText];
else if([elementName isEqualToString:#"name"] )
There is actually a fairly simple way to deal with cascading if-else statements in a language like Objective-C. Yes, you can use subclassing and overriding, creating a group of subclasses that implement the same method differently, invoking the correct implementation at runtime using a common message. This works well if you wish to choose one of a few implementations, but it can result in a needless proliferation of subclasses if you have many small, slightly different implementations like you tend to have in long if-else or switch statements.
Instead, factor out the body of each if/else-if clause into its own method, all in the same class. Name the messages that invoke them in a similar fashion. Now create an NSArray containing the selectors of those messages (obtained using #selector()). Coerce the string you were testing in the conditionals into a selector using NSSelectorFromString() (you may need to concatenate additional words or colons to it first depending on how you named those messages, and whether or not they take arguments). Now have self perform the selector using performSelector:.
This approach has the downside that it can clutter-up the class with many new messages, but it's probably better to clutter-up a single class than the entire class hierarchy with new subclasses.
Posting this as a response to Wevah's answer above -- I would've edited, but I don't have high enough reputation yet:
unfortunately the first method breaks for fields with more than one word in them -- like xPosition. capitalizedString will convert that to Xposition, which when combined with the format give you setXposition: . Definitely not what was wanted here. Here is what I'm using in my code:
NSString *capName = [elementName stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[[elementName substringToIndex:1] uppercaseString]];
SEL selector = NSSelectorFromString([NSString stringWithFormat:#"set%#:", capName]);
Not as pretty as the first method, but it works.
I have come up with a solution that uses blocks to create a switch-like structure for objects. There it goes:
BOOL switch_object(id aObject, ...)
{
va_list args;
va_start(args, aObject);
id value = nil;
BOOL matchFound = NO;
while ( (value = va_arg(args,id)) )
{
void (^block)(void) = va_arg(args,id);
if ( [aObject isEqual:value] )
{
block();
matchFound = YES;
break;
}
}
va_end(args);
return matchFound;
}
As you can see, this is an oldschool C function with variable argument list. I pass the object to be tested in the first argument, followed by the case_value-case_block pairs. (Recall that Objective-C blocks are just objects.) The while loop keeps extracting these pairs until the object value is matched or there are no cases left (see notes below).
Usage:
NSString* str = #"stuff";
switch_object(str,
#"blah", ^{
NSLog(#"blah");
},
#"foobar", ^{
NSLog(#"foobar");
},
#"stuff", ^{
NSLog(#"stuff");
},
#"poing", ^{
NSLog(#"poing");
},
nil); // <-- sentinel
// will print "stuff"
Notes:
this is a first approximation without any error checking
the fact that the case handlers are blocks, requires additional care when it comes to visibility, scope and memory management of variables referenced from within
if you forget the sentinel, you are doomed :P
you can use the boolean return value to trigger a "default" case when none of the cases have been matched
The most common refactoring suggested for eliminating if-else or switch statements is introducing polymorphism (see http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html). Eliminating such conditionals is most important when they are duplicated. In the case of XML parsing like your sample you are essentially moving the data to a more natural structure so that you won't have to duplicate the conditional elsewhere. In this case the if-else or switch statement is probably good enough.
In this case, I'm not sure if you can easily refactor the class to introduce polymorphism as Bradley suggests, since it's a Cocoa-native class. Instead, the Objective-C way to do it is to use a class category to add an elementNameCode method to NSSting:
typedef enum {
companyName = 0,
companyID,
...,
Unknown
} ElementCode;
#interface NSString (ElementNameCodeAdditions)
- (ElementCode)elementNameCode;
#end
#implementation NSString (ElementNameCodeAdditions)
- (ElementCode)elementNameCode {
if([self compare:#"companyName"]==0) {
return companyName;
} else if([self compare:#"companyID"]==0) {
return companyID;
} ... {
}
return Unknown;
}
#end
In your code, you could now use a switch on [elementName elementNameCode] (and gain the associated compiler warnings if you forget to test for one of the enum members etc.).
As Bradley points out, this may not be worth it if the logic is only used in one place.
What we've done in our projects where we need to so this sort of thing over and over, is to set up a static CFDictionary mapping the strings/objects to check against to a simple integer value. It leads to code that looks like this:
static CFDictionaryRef map = NULL;
int count = 3;
const void *keys[count] = { #"key1", #"key2", #"key3" };
const void *values[count] = { (uintptr_t)1, (uintptr_t)2, (uintptr_t)3 };
if (map == NULL)
map = CFDictionaryCreate(NULL,keys,values,count,&kCFTypeDictionaryKeyCallBacks,NULL);
switch((uintptr_t)CFDictionaryGetValue(map,[node name]))
{
case 1:
// do something
break;
case 2:
// do something else
break;
case 3:
// this other thing too
break;
}
If you're targeting Leopard only, you could use an NSMapTable instead of a CFDictionary.
Similar to Lvsti I am using blocks to perform a switching pattern on objects.
I wrote a very simple filter block based chain, that takes n filter blocks and performs each filter on the object.
Each filter can alter the object, but must return it. No matter what.
NSObject+Functional.h
#import <Foundation/Foundation.h>
typedef id(^FilterBlock)(id element, NSUInteger idx, BOOL *stop);
#interface NSObject (Functional)
-(id)processByPerformingFilterBlocks:(NSArray *)filterBlocks;
#end
NSObject+Functional.m
#implementation NSObject (Functional)
-(id)processByPerformingFilterBlocks:(NSArray *)filterBlocks
{
__block id blockSelf = self;
[filterBlocks enumerateObjectsUsingBlock:^( id (^block)(id,NSUInteger idx, BOOL*) , NSUInteger idx, BOOL *stop) {
blockSelf = block(blockSelf, idx, stop);
}];
return blockSelf;
}
#end
Now we can set up n FilterBlocks to test for the different cases.
FilterBlock caseYES = ^id(id element, NSUInteger idx, BOOL *breakAfter){
if ([element isEqualToString:#"YES"]) {
NSLog(#"You did it");
*breakAfter = YES;
}
return element;
};
FilterBlock caseNO = ^id(id element, NSUInteger idx, BOOL *breakAfter){
if ([element isEqualToString:#"NO"] ) {
NSLog(#"Nope");
*breakAfter = YES;
}
return element;
};
Now we stick those block we want to test as a filter chain in an array:
NSArray *filters = #[caseYES, caseNO];
and can perform it on an object
id obj1 = #"YES";
id obj2 = #"NO";
[obj1 processByPerformingFilterBlocks:filters];
[obj2 processByPerformingFilterBlocks:filters];
This approach can be used for switching but also for any (conditional) filter chain application, as the blocks can edit the element and pass it on.