Yicheng Wang
Yicheng Wang

Reputation: 23

How does NSrange work here?

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;
}

Upvotes: 0

Views: 451

Answers (2)

Ian MacDonald
Ian MacDonald

Reputation: 14010

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.

Upvotes: 2

Abizern
Abizern

Reputation: 150605

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.

Upvotes: 0

Related Questions