Objective-C access to floating getters with variable names

For example, I have NSArraycalled myArrayof NSString( @"a0", @"a1", @"a2")

Then, in a quick listing, I loop into my array to build the properties according to this NSStrings. I have a problem accessing these properties.

I am trying something like this:

@property (nonatomic) float a0propertyLow;
@property (nonatomic) float a0propertyHigh;
@property (nonatomic) float a1propertyLow;
@property (nonatomic) float a1propertyHigh;
..
.. etc.


for (NSString *aPos in myArray) {
    NSString *low = [NSString stringWithFormat:@"%@propertyLow",aPos];
    NSString *high = [NSString stringWithFormat:@"%@propertyHigh",aPos];
    SEL lowSel = NSSelectorFromString(low);
    SEL highSel = NSSelectorFromString(high);
    if ([self respondsToSelector:lowSel]&&[self respondsToSelector:highSel]) {
        id sumPartOne = [self performSelector:lowSel];
        id sumPartTwo = [self performSelector:highSel];
        float bla = (float)sumPartOne + (float)sumPartTwo;
    }
}

I know my code is wrong, but I don’t know how to make it work. My problem is that lowSel and highSel are getters that return float, but the selector method returns idwhich is suitable for the object, but not for floats.

, ? , , , - ( , , ), :)

.

+3
3

performSelector: , . performSelector: , :

, , , NSInvocation.

An NSInvocation , .

, , :

[self valueForKey:low];

float NSNumber.

+3

getter, double objc_msgSend_fpret():

#include <objc/runtime.h>
#include <objc/message.h>

double arg0 = objc_msgSend_fpret(self, lowSel);

( , , , ) :

void *object_getIvarPtr(id obj, const char *name)
{
    if (!obj || !name)
    {
        return NULL;
    }

    Ivar ivar = object_getInstanceVariable(obj, name, NULL);

    if (!ivar)
    {
        return NULL;
    }

    return ((char *)obj + ivar_getOffset(ivar));
}

float arg0 = *(float *)object_getIvarPtr(self, [lowSel UTF8String]);

, .

+1

One way you can do this is to convert your floats to objects at runtime, for example: -

NSString *str=[NSSTring stringWithFormat:@"%f",yourFloatValue];

and then u can extract it using

[str floatValue];
-1
source

All Articles