0

I watched a video about ios7 programming and saw piece of codes below.

I can not really understand how the variable range works here.

We create a NSrange variable range and never give it a value, so I think the &range pointer should return nil.

Then how can it be used in effectiveRange and what is the value in range.location and range.length?

Thank you so much for help!

- (NSMutableAttributedString *)charactersWithAttribute:(NSString *)attributeName
{
    NSMutableAttributedString *characters = [[NSMutableAttributedString alloc] init];

    int index = 0;

    while(index < self.textToAnalyze.length)
    {
        NSRange range;
        id value = [self.textToAnalyze attribute:attributeName atIndex:index      effectiveRange:&range];
        if(value)
        {
            [characters appendAttributedString: [self.textToAnalyze  attributedSubstringFromRange:range]];
            index = range.location+range.length;
        }
        else{
            index++;
        }
    }

    return characters;
}
  • Look at the code for `attribute:atIndex:effectiveRange:`. Notice what it does with the passed in `NSRange` pointer. – rmaddy Oct 17 '14 at 18:15

2 Answers2

2

Declaring NSRange range allocates memory on the stack (in the local scope). This memory is tied to a memory address that is accessed by &range. When you pass this memory address into the method, the method uses the address as the location to which it assigns values. After the method returns, the memory associated with range will now have been assigned values so when you access them (to send them to attributedSubstringFromRange:), everything will work as expected.

Ian MacDonald
  • 13,472
  • 2
  • 30
  • 51
0

NSRange is not an object it us a strict so declaring it sets it up with default values. It doesn't return nil when you declare it.

Abizern
  • 146,289
  • 39
  • 203
  • 257