Using NSGlyph and memory allocation

こ雲淡風輕ζ 提交于 2019-12-31 04:49:05

问题


in a method to track line breaks frequently, for a NSTextView visibleRect, i am allocating memory for NSGlyph to use NSLayoutManager getGlyphs:range:.

should/can i find out how much memory this should be since i have a reference for the range (without affecting layout), and also, what kind of cleanup should happen -- running with ARC ?

the code (which runs on a main queue) :

    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;

回答1:


With the NSGlyph glyphs[5000] notation, you're allocating the memory on the stack. But instead of 5000 glyphs it only has to hold visibleRange.length + 1 glyphs:

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.

And because it is on the stack, you don't have to worry about freeing the memory—because never malloced memory; it is freed automatically when leaving the function—even without ARC

So it should work, if you write it like this:

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


来源:https://stackoverflow.com/questions/16675997/using-nsglyph-and-memory-allocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!