Search code examples
objective-cobjectobject-type

How can I have one object and change it's type at runtime


I have a method that is called by 3 different methods.

Each method indicates what kind of data it wants to receive back from the method via a flag. In this example lets call the flag 'objectType'.

The 'calledMethod' needs to look at the objectType and create the correct object based upon this.

The 'calledMethod' then needs to return the same objectType that it received, so that the calling method gets the correct objectType.

I have included sample code below, that I know is not correct but it gives you the sense of what I am trying to achieve. Note that all 3 objects have the 'testInt' objectKey.

eg.

-(NSObject *)calledMethod : (int)objectType
{
    NSObject *einStein;

    switch (objectType)
    {
        case 1: // this is an NSUserDefaults object
            einStein = [NSUserDefaults standardUserDefaults];
            break;
        case 2: // this is an PFUser object
            einStein = [PFUser currentUser];
            break;
        case 3: // this is a custom object
            einStein = [TestData personData];
            break;
        default:
            break;
    }

    int *testCnt = [einStein objectForKey@"testInt"];
    testCnt = testCnt++;
    [einStein setObject:testCnt forKey:@"testInt"];
    return einStein;
}

Solution

  • I think Sinisa is probably correct re using Factory Patterns, but it was too complicated for me to implement in the time I had, so will try at some point in the future