Question

I am using GameKit for networking in my C++ application (created an Objective-C class for managing GameKit networking), but the problem is that GameKit uses NSString (not a C++ type) to identify peers (peerID). I have tested GameKit a lot and in my practice peerID is always a number (eg. 754569949). Is it safe to lexically cast peerID to uint32_t? Are there any cases where peerID is not a number?

Was it helpful?

Solution

I see a couple of parts to your question: 1) parsing an int from peerID string; 2) maintaining association between your internals ids and peerIDs.

If you need to get peerID into your C++ code and then be able to convert it back to NSString for use with GameKit framework, you shouldn't make any more assumptions about peerID's contents than the official docs provide.

In other words, if you absolutely have to use ints, provide a way to map peerIDs to your internal identifiers. But keep peerIDs around and associated with your identifiers to be able to map the other way -- from your id back to NSString.

Making a map of NSString -> uint32_t might be one way to go about it.

The above mostly covers the 2nd part I mentioned in the first sentence. Now let's consider if it's save to parse peerID as an integer.

If you need to guarantee that a particular peerID will always map to the same uint32_t, you either assume peerID represents a number that will always fit into uint32_t, or you compute a hash of the string. There are problems with both approaches. Such a short hash might have collisions in real use. On the other hand, your system might brake one day when Apple decides to extend their peerIDs to also include letters.

So I can't really make a decision for you, I've just tried to lay out the possibilities you might want to consider. I'd strongly suggest you to find a way to use original peerID, possibly converted to a C++ string type.

OTHER TIPS

The problem is that for compatibility with other parts of code, I need to identify clients by integer, not string

If you have to get an integer out of these strings, in the absence of any guarantee it will always be a number, simply build a table of known IDs and assign indexes to them.

57483829 => 0
42937422 => 1
3333fghh => 2

You could use two std::maps to quickly convert between the two representations.

Simply convert the NSString to a string that's more C++ friendly. Alternatively, do the translation and maintain the indexes in Objective-C first and you can give your C++ code an index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top