I’m working on a category for NSArray and one of the functions I’ve implemented is designed to return the number of strings (or not numbers) in the array. This all works fine, but my question is about the usage of NSNotFound as a return in the event that the input array’s count is zero.
Apple’s docs state:
NSNotFound is typically used by various methods and functions that
search for items in serial data and return indices, such as characters
in a string object or ids in an NSArray object.
This makes complete sense if I were to use indexOfObject: for an item that wasn’t in the array. But, is using NSNotFound in the context demonstrated below correct usage? Sure I could just return zero and call it a day, but it would be helpful seeing 2147483647 and immediately knowing where the problem is.
- (NSUInteger)countOfStringsInArray {
NSUInteger currentCount = 0;
if ([self count] > 0) {
for (id obj in self) {
if (![obj integerValue]) {
currentCount ++;
}
}
return currentCount;
}
return NSNotFound;
}
No, not in this case. The method in the example returns a count. You would consider using/returning
NSNotFound(for example) on a method which returns an index, where0is also a valid index and thus a misrepresentative result.So “Yes, you should simply return 0 and the return type should be unsigned (NSUInteger)”, since
NSNotFoundshould not be associated to a count. That really covers your cases without dependance on a magic value.If you favor knowing where the problem is (and I do this myself quite often), I find it preferable to instead just consider it a programmer error to call the method when the collection is empty.