libs-base/Tests/base/KVC/safe_caching.m
Hugo Melder 6eef1c3289
NSKeyValueCoding: Safe-Caching for -[NSObject valueForKey:] (#445)
* KVC Caching Implementation

* Do not ignore struct name when comparing type encoding as NSPoint and NSSize have the same layout

* Use fast-path when using Objective-C 2

* Guard old ValueForKey function when using the fast-path

* Add basic NSKeyValueCoding tests

* Update Copyright Years

* NSKeyValueCoding+Caching: Add Versioning to IVar Slot

* safe_caching: Remove Guards

* Add type encoding helper header

* Rename geometry structs (NSRect, NSPoint, NSSize) for toll-free bridging with CoreGraphics

* Move CG struct definitions to CFCGTypes.h

* Update known struct encoding prefixes

* Windows 64-bit is LLP64 and not LP64

* Re-order to avoid complier warning

---------

Co-authored-by: rfm <richardfrithmacdonald@gmail.com>
2024-10-29 14:12:34 +01:00

56 lines
1.1 KiB
Objective-C

#import <Foundation/NSKeyValueCoding.h>
#import <Foundation/NSValue.h>
#import <objc/runtime.h>
#import "Testing.h"
@interface TestClass : NSObject
- (float)floatVal;
@end
@implementation TestClass
- (float)floatVal
{
return 1.0f;
}
@end
static float
getFloatValIMP(id receiver, SEL cmd)
{
return 2.0f;
}
void
testInstallingNewMethodAfterCaching(void)
{
TestClass *obj = [TestClass new];
START_SET("Installing Methods after initial Cache")
// Initial lookups
PASS_EQUAL([obj valueForKey:@"floatVal"], [NSNumber numberWithFloat:1.0f],
"Initial lookup has the correct value");
// Slots are now cached
// Register getFloatVal which should be used if available according to search
// pattern
SEL sel = sel_registerName("getFloatVal");
class_addMethod([TestClass class], sel, (IMP) getFloatValIMP, "f@:");
PASS_EQUAL([obj valueForKey:@"floatVal"], [NSNumber numberWithFloat:2.0f],
"Slot was correctly invalidated");
END_SET("Installing Methods after initial Cache")
[obj release];
}
int
main(int argc, char *argv[])
{
testInstallingNewMethodAfterCaching();
return 0;
}