NSValue:getValue: strange behavior,why this happens?

后端 未结 2 728
情深已故
情深已故 2021-01-14 18:25

I try to pass CGRect to NSInvocation (setArgument:atIndex:). I wrap it by NSValue, push to the NSArry,then get from NSArray and use NSValue (getValue:). Calling of (getValue

2条回答
  •  情深已故
    2021-01-14 18:51

    You can't fit an NSRect into a void*. The correct code would be:

    NSRect buffer;
    [currentVal getValue:&buffer];
    

    Or alternatively, if you don't know the contents of the NSValue object:

    NSUInteger bufferSize = 0;
    NSGetSizeAndAlignment([currentVal objCType], &bufferSize, NULL);
    void* buffer = malloc(bufferSize);
    [currentVal getValue:buffer]; //notice the lack of '&'
    //do something here
    free(buffer);
    

    The value for i is changing because your code causes an overflow into other stack-allocated variables.

提交回复
热议问题