[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Strings and NSRanges

From: Richard Frith-Macdonald
Subject: Re: Strings and NSRanges
Date: Mon, 20 Nov 2006 08:24:04 +0000

On 19 Nov 2006, at 15:45, Graham J Lee wrote:


I'm trying to implement NSNumberFormatter's -stringForObjectValue: as I said on bug-. However, I'm having trouble with parsing the format string and I expect it has more to do with my confusion than it does with any other problems ;-).

The Cocoa behaviour for the formatter is that if the character '.' appears anywhere in the format string, this "turns on" displaying the fractional part of the number (unless allowsFloats is false) with as many decimal places as the are placeholder characters (# or a number) to the *immediate* right of the *rightmost* '.' in the format string. So I'm doing this:

if ([self allowsFloats] && (NSNotFound != [useFormat rangeOfString:@"." ].location))
decimalPlaceRange = [useFormat rangeOfString: @"." options: NSBackwardsSearch]; while ([placeHolders characterIsMember: [useFormat characterAtIndex: NSMaxRange(decimalPlaceRange)]])
          if (NSMaxRange(decimalPlaceRange) == [useFormat length])
      if (0 != decimalPlaces)
        displayFractionalPart = YES;

which doesn't work...decimalPlaces ends up being some garbage value such as 2412439 when the length of the string is only, say, 7. For that to happen then the length of the *range* must have always been greater than the length of the string (so that the if(NSMaxRange (...)...) line never breaks the loop) and the loops *starts* by reading nonsense memory outside the string. Why would that happen?

It's hard to tell without a complete test program ... but I can make a couple of observations.

1. the loop should not be able to start by 'reading nonsense memory outside the string' because the -characterAtIndex: method should raise an exception if asked to refer to an index outside the string. 2. if useFormat is nil then the code is totally broken since sending a message to a nil object is defined to return nil ... but where the method is expected to return a range this means that the resulting behavior is undefined. On sparc it will cause an immediate crash, but on intel I think it probably just means the returned range contains garbage ... which would explain your symptoms.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]