Anyway to get string from variable name?

后端 未结 5 1398
不思量自难忘°
不思量自难忘° 2020-11-29 07:48

Say I have my class

@interface Person : NSObject { NSString *name; }

I need to get the name of NSString\'s within my class



        
相关标签:
5条回答
  • 2020-11-29 08:05

    You might use preprocessor stringification and a bit of string twiddling:

    NSUInteger lastIndexAfter(NSUInteger start, NSString *sub, NSString *str) {
        NSRange found = [str rangeOfString:sub options:NSBackwardsSearch];
        if(found.location != NSNotFound) {
            NSUInteger newStart = NSMaxRange(found);
            if(newStart > start)
                return newStart;
        }
        return start;
    }
    
    NSString *lastMember(NSString *fullName) {
        if(!fullName) return nil;
    
        NSUInteger start = 0;
        start = lastIndexAfter(start, @".", fullName);
        start = lastIndexAfter(start, @"->", fullName);
    
        return [fullName substringFromIndex: start];
    }
    
    #define NSStringify(v) (@#v)
    #define _NameofVariable_(v) lastMember(NSStringify(v))
    
    0 讨论(0)
  • 2020-11-29 08:07

    If the person object is exposed as a property of the class, you can use objc_msgSend to get the value.

    So, if you could access person using

    [object person]
    

    You could also do

    objc_msgSend(object, "person")
    

    For more details on message sending, including how to pass arguments to methods, see the Objective-C Runtime Programming Guide section on Messaging

    0 讨论(0)
  • 2020-11-29 08:10

    As easy as

    #define VariableName(arg) (@""#arg)

    Then you do:

    NSObject *obj;
    NSString *str = VariableName(obj);
    NSLog(@"STR %@", str);//obj
    
    0 讨论(0)
  • 2020-11-29 08:20

    You can get the names of a class's instance variables with the Objective-C runtime API function class_copyIvarList. However, this is rather involved, rarely done and almost never the best way to accomplish something. If you have a more specific goal in mind than mere curiosity, it might be a good idea to ask about how to accomplish it in Objective-C.

    Also, incidentally, person.name doesn't specify an instance variable in Objective-C — it's a property call. The instance variable would be person->name.

    0 讨论(0)
  • 2020-11-29 08:21

    The following works as a macro:

    #define STRINGIZE(x) #x
    
    0 讨论(0)
提交回复
热议问题