函数里 { } 的好处

最近在apple demo 的时候 发现 apple 的工程师 都喜欢在函数内部使用 {} 在 {} 内部做一些new 和 create 起初没有太在意 感觉是多余的
今天定眼一看 发现 蛮好的 对内存的释放 起到了很好的作用

code

/// Initialize with the MetalKit view from which we'll obtain our Metal device
- (nonnull instancetype)initWithMetalKitView:(nonnull MTKView *)mtkView
{
    self = [super init];
    if(self)
    {
        _device = mtkView.device;
        mtkView.clearColor = MTLClearColorMake(0.0, 0.5, 0.5, 1.0f);

        // Create a vertex buffer, and initialize it with our generics array
        {
            static const AAPLVertex vertexData[] =
            {
                //      Vertex      |  Texture    |         Vertex
                //     Positions    | Coordinates |         Colors
                { {  .75f,  -.75f }, { 1.f, 0.f }, { 0.f, 1.f, 0.f, 1.f } },
                { { -.75f,  -.75f }, { 0.f, 0.f }, { 1.f, 1.f, 1.f, 1.f } },
                { { -.75f,   .75f }, { 0.f, 1.f }, { 0.f, 0.f, 1.f, 1.f } },
                { {  .75f,  -.75f }, { 1.f, 0.f }, { 0.f, 1.f, 0.f, 1.f } },
                { { -.75f,   .75f }, { 0.f, 1.f }, { 0.f, 0.f, 1.f, 1.f } },
                { {  .75f,   .75f }, { 1.f, 1.f }, { 1.f, 1.f, 1.f, 1.f } },
            };

            _vertexBuffer = [_device newBufferWithBytes:vertexData
                                                 length:sizeof(vertexData)
                                                options:MTLResourceStorageModeShared];

            _vertexBuffer.label = @"Vertices";
        }

        // Create texture to apply to the quad
        {
            NSError *error;

            MTKTextureLoader *textureLoader = [[MTKTextureLoader alloc] initWithDevice:_device];

            _texture = [textureLoader newTextureWithName:@"Text"
                                             scaleFactor:1.0
                                                  bundle:nil
                                                 options:nil
                                                   error:&error];

            NSAssert(_texture, @"Could not load foregroundTexture: %@", error);

            _texture.label = @"Text";
        }

        // Create sampler to use for texturing
        {
            MTLSamplerDescriptor *samplerDesc = [MTLSamplerDescriptor new];
            samplerDesc.minFilter = MTLSamplerMinMagFilterLinear;
            samplerDesc.magFilter = MTLSamplerMinMagFilterLinear;
            samplerDesc.mipFilter = MTLSamplerMipFilterNotMipmapped;
            samplerDesc.normalizedCoordinates = YES;
            samplerDesc.supportArgumentBuffers = YES;

            _sampler = [_device newSamplerStateWithDescriptor:samplerDesc];
        }

        uint16_t bufferElements = 256;

        // Create buffers used to make a pattern on our quad
        {
            _indirectBuffer = [_device newBufferWithLength:sizeof(float) * bufferElements
                                                   options:MTLResourceStorageModeShared];

            float * const patternArray = _indirectBuffer.contents;

            for(uint16_t i = 0; i < bufferElements; i++) {
                patternArray[i] = ((i % 24) < 3) * 1.0;
            }

            _indirectBuffer.label = @"Indirect Buffer";
        }

        // Create our render pipeline and argument buffers
        {
            NSError *error;

            id<MTLLibrary> defaultLibrary = [_device newDefaultLibrary];

            id <MTLFunction> vertexFunction = [defaultLibrary newFunctionWithName:@"vertexShader"];

            id <MTLFunction> fragmentFunction = [defaultLibrary newFunctionWithName:@"fragmentShader"];

            id <MTLArgumentEncoder> argumentEncoder =
                [fragmentFunction newArgumentEncoderWithBufferIndex:AAPLFragmentBufferIndexArguments];

            NSUInteger argumentBufferLength = argumentEncoder.encodedLength;

            _fragmentShaderArgumentBuffer = [_device newBufferWithLength:argumentBufferLength options:0];

            _fragmentShaderArgumentBuffer.label = @"Argument Buffer";

            [argumentEncoder setArgumentBuffer:_fragmentShaderArgumentBuffer offset:0];

            [argumentEncoder setTexture:_texture atIndex:AAPLArgumentBufferIDExampleTexture];
            [argumentEncoder setSamplerState:_sampler atIndex:AAPLArgumentBufferIDExampleSampler];
            [argumentEncoder setBuffer:_indirectBuffer offset:0 atIndex:AAPLArgumentBufferIDExampleBuffer];

            uint32_t *numElementsAddress = [argumentEncoder constantDataAtIndex:AAPLArgumentBufferIDExampleConstant];

            *numElementsAddress = bufferElements;

            // Set up a descriptor for creating a pipeline state object
            MTLRenderPipelineDescriptor *pipelineStateDescriptor = [[MTLRenderPipelineDescriptor alloc] init];
            pipelineStateDescriptor.label = @"Argument Buffer Example";
            pipelineStateDescriptor.vertexFunction = vertexFunction;
            pipelineStateDescriptor.fragmentFunction = fragmentFunction;
            pipelineStateDescriptor.colorAttachments[0].pixelFormat = mtkView.colorPixelFormat;
            _pipelineState = [_device newRenderPipelineStateWithDescriptor:pipelineStateDescriptor
                                                                     error:&error];

            NSAssert(_pipelineState, @"Failed to create pipeline state: %@", error.localizedDescription);

        }

        // Create the command queue
        _commandQueue = [_device newCommandQueue];
    }

    return self;
}

你会发现 在这个函数中 多次使用 {}
产生局部区域 加速内存的释放 标记一下 提醒自己 以后多使用 {}
优化代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值