Search code examples
iosobjective-c

Access name of instantiated object without additional property nor init method


In the below BNREmployee.m implementation file I am trying to override the default description and would like to be able to access the object name john assigned at instantiation in the main.m file. Is there a way to do this WITHOUT creating a separate "name" property or instance variable, and WITHOUT creating a separate init method where that name would be passed in?

main.m file:

#import <Foundation/Foundation.h>
#import "BNRPerson.h"
#import "BNREmployee.h"
#import "BNREmployer.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        BNREmployee *john = [BNREmployee new];
        BNREmployer *costco = [BNREmployer new];
        [john setEmployer:costco];
        [costco setEmployeesList:[NSMutableSet setWithObject:john]];
        
        NSLog(@"employee: \n%@", john);
    }
    return 0;
}

BNREmployee.m file:

#import "BNREmployee.h"

@implementation BNREmployee

-(NSString*) description
{
    return [NSString stringWithFormat:@"<Employee %@ with id: %d and employer: %@", [self ???***???], self.employeeId, self.employer];
}
@end

Solution

  • No, it's not possible for a class to know the name of a variable it's been assigned to. Keep in mind that you can assign one instance of BNREmployee (or any other class) to more than one variable.

    BNREmployee *bob = [BNREmployee new];
    BNREmployee *john = bob;
    NSLog(@"employee = %@", bob);
    NSLog(@"employee = %@", john);
    

    In this case, how would the description method know the name? The one instance of the class has been assigned to two different variables.

    Relying on the variable name makes little sense. If you want the BNREmployee class to keep track of a name then you must add a name property to the class. That's the whole point of a class - to keep track of state/data.

    tl;dr - you can't do what you want. You must add a name property and optionally a custom init that lets you assign a name on creation.