NSrange如何在这里工作?

时间:2014-10-17 18:11:42

标签: ios objective-c nsrange

我观看了一段关于ios7编程的视频,并在下面看到了一段代码。

我无法真正理解变量范围如何在这里起作用。

我们创建一个NSrange变量范围并且从不给它一个值,所以我认为& range指针应该返回nil。

那么如何在effectiveRange中使用它,range.location和range.length中的值是什么?

非常感谢您的帮助!

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

2 个答案:

答案 0 :(得分:2)

声明NSRange range在堆栈上分配内存(在本地范围内)。此内存绑定到&range访问的内存地址。将此内存地址传递给方法时,该方法使用该地址作为其分配值的位置。方法返回后,与range关联的内存现在将被赋值,因此当您访问它们时(将它们发送到attributedSubstringFromRange:),一切都将按预期工作。

答案 1 :(得分:0)

NSRange不是我们严格的对象,因此声明它使用默认值进行设置。当你声明它时,它不会返回nil。