Created
July 9, 2013 21:00
-
-
Save markd2/5961259 to your computer and use it in GitHub Desktop.
Example showing the use of accessing the indexed ivars.
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
| #import <Foundation/Foundation.h> | |
| #import <objc/runtime.h> | |
| // This stuff won't work with ARC, so make sure it's turned off. | |
| // clang -g -fno-objc-arc -framework Foundation -o indexedivars indexedivars.m | |
| @interface Stuffage : NSObject { | |
| int _extraCount; | |
| } | |
| - (id) initWithExtraSpace: (int) extraCount; | |
| - (int) stuffAtIndex: (unsigned int) index; | |
| @end // Stuffage | |
| @implementation Stuffage | |
| - (id) initWithExtraSpace: (int) extraCount { | |
| if ((self = [super init])) { | |
| _extraCount = extraCount; | |
| int *extra = object_getIndexedIvars (self); | |
| for (int i = 0; i < extraCount; i++) { | |
| extra[i] = i * 100; | |
| } | |
| } | |
| return self; | |
| } // initWithExtraSpace | |
| - (int) stuffAtIndex: (unsigned int) index { | |
| assert (index < _extraCount); | |
| int *extra = object_getIndexedIvars (self); | |
| return extra[index]; | |
| } // stuffAtIndex | |
| @end // Stuffage | |
| int main (void) { | |
| Stuffage *stuff = class_createInstance ([Stuffage class], sizeof(int) * 30000); | |
| // Stuffage *stuff = class_createInstance ([Stuffage class], 0); | |
| stuff = [stuff initWithExtraSpace: 30000]; | |
| printf ("%d %d %d %d\n", | |
| [stuff stuffAtIndex: 1], | |
| [stuff stuffAtIndex: 25], | |
| [stuff stuffAtIndex: 300], | |
| [stuff stuffAtIndex: 29999]); | |
| typedef struct ExpandOMatic { | |
| char *name; | |
| int footCount; | |
| float footSizes[0]; | |
| } ExpandOMatic; | |
| ExpandOMatic *nofoot = malloc (sizeof(ExpandOMatic)); | |
| nofoot->name = "nochan"; | |
| nofoot->footCount = 0; | |
| int footCount = 30; | |
| ExpandOMatic *lotsOfFeet = malloc (sizeof(ExpandOMatic) + sizeof(float) * footCount); | |
| lotsOfFeet->name = "footloose"; | |
| lotsOfFeet->footCount = footCount; | |
| for (int i = 0; i < footCount; i++) { | |
| lotsOfFeet->footSizes[i] = random() % 15; | |
| } | |
| printf ("size of expand-o-matic: %zu\n", sizeof(ExpandOMatic)); | |
| return 0; | |
| } // main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment