質問

I am taking an NSInteger (long int) from a method and using it as a parameter in a method, which takes an NSUInteger (unsigned int).

NSInteger input = [someObject someMethod];
[someOtherObject someOtherMethodWithNSUInteger: input];

This isn't a great idea. What if input is a negative number? How can I do this in a way that is a good practice? Sure, I could just go

[someOtherObject someOtherMethodWithNSUInteger: (NSUInteger)input];

But that's not a good solution because if input is negative, it will not bound it to zero. I could resort to it if there was no other way, but I would rather not.

Solutions that will not work:

Why can't I just make someMethod return an NSUInteger? Or make someOtherMethodWithNSUInteger: take an NSInteger? It's because I don't own them, they are a part of Cocoa Touch.

What about returning nil and using NSError or throwing an exception? The method that I am putting this code in conforms to a protocol, so I can't add an (NSError**) parameter to the method, and returning nil without an NSError explaining why seems like a bad idea because since I don't have access to someMethod's or someOtherMethod's source code, there would be nothing for me to even fix. And if I throw an exception, there is no way for me to catch it because this is code will be used by a closed class who made the protocol.

How can I fix this type conversion problem?

役に立ちましたか?

解決

I think the answer somewhat straightforward, and it's basically what you said yourself.

If someOtherMethodWithNSUInteger expects unsigned and the only thing you have is a signed value (returned from someMethod) then two things will happen: (1) half of the possible values expected will never be used, and (2) half of the possible values returned are invalid. No matter what method you use you will always have these issues. So the easiest thing to do is use a simple type-casting, and trim negative values to prevent them being interpreted as very large positive values.

[someOtherObject someOtherMethodWithNSUInteger: (NSUInteger)MAX(input,0)];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top