Last active
February 3, 2023 15:29
-
-
Save theoknock/469466650f4de02ca86a001ed9ee4352 to your computer and use it in GitHub Desktop.
Blocks that create and return generic references and pointers to objects of any type. Demonstrates the use of id and const void * and CFBridgingRetain and CFBridgingRelease for generic programming purposes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Returns a generic pointer to an object of any type | |
const void * (^object_t)(const unsigned long) = ^ const void * (const unsigned long index) { | |
UIButton * button; | |
[button = [UIButton new] setTag:index]; | |
printf("\nbutton == %p\n\n", &button); | |
return (const id *)CFBridgingRetain(button); | |
}; | |
// Outer block retains a generic pointer reference to an object of any type for subsequent calls to inner block | |
// Inner block returns the object referenced by the generic pointer retained by outer block | |
id _Nonnull (^(^ _Nonnull persistent_object_t)(const void * _Nonnull))(void) = ^ (const void * _Nonnull object_t) { | |
return ^ id _Nonnull (void) { | |
return (__bridge id _Nonnull)((__bridge const void * _Nonnull)CFBridgingRelease(object_t)); | |
}; | |
}; | |
typedef id _Nonnull (^object)(void); // Type definition for references to the inner block returned by the outer block (for delayed execution and storing as an element to a collection) | |
// Returns the object referenced by the generic pointer parameter | |
id _Nonnull (^ _Nonnull object_ref)(const void * _Nonnull) = ^ (const void * _Nonnull object_t) { | |
printf("\nconst void * _Nonnull object_t == %p\n", object_t); | |
return (__bridge id _Nonnull)((__bridge const void * _Nonnull)CFBridgingRelease(object_t)); | |
}; | |
// Invokes each block (except persistent_object_t) | |
static void(^generics)(void) = ^{ | |
const void * obj_t = object_t(1); // a generic pointer to a UIButton object | |
id _Nonnull obj = object_ref(obj_t); // a generic reference to the UIButton object pointed to by obj_t (cast to UIButton * prior to use) | |
printf("\nobject_t == %p\n", obj_t); // | |
printf("\nobject == %p\n\n", &obj); | |
object persistent_obj = persistent_object_t(obj_t); // retains the value of a generic pointer reference | |
obj = persistent_obj(); | |
}; | |
/* | |
// Console output displaying the pointer value of a UIButton object and the value of the pointer to the object | |
// to validate object (and pointer reference) persistence between block invocations | |
button == 0x16db38868 | |
const void * _Nonnull object_t == 0x102a0b9a0 | |
object_t == 0x102a0b9a0 | |
object == 0x16db38898 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment