Skip to content

Objective-C Adapter From NSInteger To id When Using performSelector withObject

As an Objective-C beginner it is not so easy to understand how to correctly cast things, so I needed some research to get it solved. I hope that post makes it easier for you. My problem occurred trying to feed the performSelector withObject message with an enum.

I implemented my nice HTTP Request class, which I will explain in the next Posts completely. So, everything worked well as long as my web server was reachable… so I thought, adding error handling should be easy too. But there was some small complication.

What I planned to do was: Whenever a HTTP communication error occurs, I don’t wanted to give up, but I wanted my request to be rescheduled. This way I could retry for a while having the chance to successfully process the request in case the web server becomes available again.

So I started adding an error handling block to my controller class with the intention to reschedule the following method after a delay in case of an error:

So far so good. But do you recognise it?

Correct! My method requestInfosAndPersistByMonsterType takes a message of type MonsterTypes (NSInteger) that is defined like this:

This following code I tried at first compiled correctly, but I very quickly recognised that it has errors. 

I tried to call requestInfosAndPersistByMonsterType directly using a cast from Integer to NSNumber. This is really pretty straightforward:

But somehow, the NSNumber object was dereferenced incorrectly this way and the next message processing used the NSNumber object’s address instead of the referenced number value. This led to very obscure results.

I tried a lot, back and forth. Actually, a (for me) good solution was to built an adapter. When you look at the part scheduling to invoke the request method again you will find a method monsterTypeFromObject instead of requestInfosAndPersistByMonsterType.

Alright, now let’s look into the adapter monsterTypeFromObject that is called now after 5 secs:

Here you go. As you see, I explicitly need to touch every of my custom types again and then call the required method requestInfosAndPersistByMonsterType again. Using this little adapter, everything works out nicely and I can savely cast a NSNumber to my own MonsterTypes.

Drawback, every new type of a monster now needs to be added to this adapter class, sadly. When I find a solution to this also, I will let you know.

 

I used this information sources:
http://stackoverflow.com/questions/6879473/how-can-i-cast-an-integer-to-an-id-in-ios
http://stackoverflow.com/questions/6883859/performselector-argument-2-makes-pointer-from-integer-without-cast/6884165#6884165
http://stackoverflow.com/questions/10073740/objective-chow-to-converting-int-to-id-for-selectors-object