gpt4 book ai didi

cocoa - 使用 NSGlyph 和内存分配

转载 作者:行者123 更新时间:2023-12-03 17:12:49 28 4
gpt4 key购买 nike

经常跟踪换行符的方法中,对于 NSTextView visibleRect,我正在为 NSGlyph 分配内存> 使用 NSLayoutManager getGlyphs:range:

我应该/可以找出这应该有多少内存,因为我有范围的引用(不影响布局),而且,应该进行什么样的清理——使用ARC运行?

代码(在主队列上运行):

    NSLayoutManager *lm = [self.textView layoutManager];
NSTextContainer *tc = [self.textView textContainer];
NSRect vRect = [self.textView visibleRect];
NSRange visibleRange = [lm glyphRangeForBoundingRectWithoutAdditionalLayout:vRect inTextContainer:tc];
NSUInteger vRangeLoc = visibleRange.location;
NSUInteger numberOfLines;
NSUInteger index;
NSGlyph glyphArray[5000]; // <--- memory assigned here
NSUInteger numberOfGlyphs = [lm getGlyphs:glyphArray range:visibleRange];
NSRange lineRange;
NSMutableIndexSet *idxset = [NSMutableIndexSet indexSet];
for (numberOfLines = 0, index = 0; index < numberOfGlyphs; numberOfLines++) {
(void)[lm lineFragmentRectForGlyphAtIndex:index effectiveRange:&lineRange withoutAdditionalLayout:YES];
[idxset addIndex:lineRange.location + vRangeLoc];
index = NSMaxRange(lineRange);
}
self.currentLinesIndexSet = idxset;

最佳答案

使用 NSGlyph glyphs[5000] 表示法,您可以在堆栈上分配内存。但它只需要保存 visibleRange.length + 1 字形,而不是 5000 个字形:

glyphArray

On output, the displayable glyphs from glyphRange, null-terminated. Does not include in the result any NSNullGlyph or other glyphs that are not shown. The memory passed in should be large enough for at least glyphRange.length+1 elements.

而且因为它在堆栈上,所以您不必担心释放内存——因为从未分配过内存;当离开函数时它会自动释放——即使没有 ARC

如果你这样写,它应该可以工作:

NSLayoutManager *lm = ...
NSRange glyphRange = ...
NSGlyph glyphArray[glyphRange.length + 1];
NSUInteger numberOfGlyphs = [lm getGlyphs:glyphArray range:glyphRange];
// do something with your glyphs

关于cocoa - 使用 NSGlyph 和内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16675997/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com