2

What is the correct way to implement classes in an Universal App?

I currently have two xib (one for each device), each xib calls the same class and inside that class I have a conditional statement checking what type of device is currently running the app and do the corresponding code for each one.

I'm confused if this is the correct structure, or do I have to create a base class and then extend that class for each of the devices to only overwrite what corresponds to each one?

Angie
  • 475
  • 2
  • 6
  • 20

1 Answers1

1

I personally try to reuse code where I can but many developers do like to create separate classes for iPhone and iPad versions to avoid "spaghetti code". It completely depends on the complexity of the app you are writing. If it's a simple app then I see no reason to just provide logic to test for the device and execute different code based on that vs creating multiple classes for each. Although, there are many benefits to creating separate code for each such as unit testing or easy updating of iPad specific code and vice versa. I have seen successful developers use both methodologies and both work well if you document and pragma mark your code correctly.

Here is an example of using diff classes

You can always just create a simple class that returns the device type as well if typing out the full test bothers people. This is handy if you want to test for things like iPod and other device types. Most times than not this is the approach I use unless the project is very large and the classes begin to feel cluttered.

// TestDevice.h
@interface TestDevice : NSObject

+ (BOOL)isIpad;

@end

// TestDevice.m
#import "TestDevice.h"

@implementation TestDevice

+ (BOOL)isIpad
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        return YES;

    return NO;
}

@end

Then just add it to your .pch and you can reuse it anywhere in the app by calling...

if ([TestDevice isIpad]) {
    // Something
}
else {
     // Something else
}
Mark McCorkle
  • 9,349
  • 2
  • 32
  • 42