ios - NSrange 在这里如何工作?

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

最佳答案

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

关于ios - NSrange 在这里如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26430997/

相关文章:

ios - 使用自定义 NSURLProtocol 和 HTTP 代理处理重定向

objective-c - 使用偏移量获取 NSString 中字符的索引并在 Objective-C 中使用子字符串

ios - 在 iOS 中使用各种验证来验证字符串

ios - NSMakeRange导致应用程序锁定;表现慢

objective-c - 在部分之间移动一行

ios - UIDocumentPickerViewController导入SSL证书

ios - 无法在 Xcode 6.4 和 Xcode 7 中构建模块 UIKIT

ios - UITableViewCell的setSelected方法中的animateWithDuration不起作用

ios - 将 swift 对象转换为 JSON 字符串

ios - stub 方法不适用于 OCMock3.4