views:

223

answers:

2

I've tried this

NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString: myString];
[myCharSet count];

But get a warning that NSCharacterSet may not respond to count. This is for desktop apps and not iPhone, which I think the above code works with.

A: 

That should not work on the iPhone either, as NSCharacterSet is not a subclass of NSSet on either platform.

If you really need to get a count why not subclass NSSet, add the value, then have a method that returns that as an NSCharacterSet on demand for use in anything that needs a character set?

Kendall Helmstetter Gelner
NSSet is a class cluster and is therefore not easily (or practically) subclassed.
Dave DeLong
Is there not a simple technique for getting a count of all characters within a string?
4thSpace
+8  A: 

I might be missing something here, but what's wrong with simply doing:

NSUInteger characterCount = [myString length];

To just get the number of characters in a string, I don't see any reason to mess around with NSCharacterSet.

Matt Ball
Just to be clear- `-length` returns `the number of Unicode characters in the receiver.` (as defined by the `NSString` documentation). Technically, the documentation is wrong because it actually returns `the number of UTF-16 Code Units` and not `the number of Unicode characters`. This distinction is unimportant for the vast majority of programmers and uses, but it does have important consequences. For example, `[@"\U0010ffff" length]` returns `2` even though it contains a single Unicode character. `characterAtIndex:` for `0` and `1` returns `0xdbff` and `0xdfff`, respectively.
johne