Skip to content

Instantly share code, notes, and snippets.

@evanlong
Created January 28, 2012 03:48
Show Gist options
  • Save evanlong/1692489 to your computer and use it in GitHub Desktop.
Save evanlong/1692489 to your computer and use it in GitHub Desktop.
partial class example
// Started here
class Reader : NSObject {}
class PDFReader_Shared : Reader {}
class PDFReader_iPad : PDFReader_Shared {}
class PDFReader_iPhone : PDFReader_Shared {}
class TextReader_Shared : Reader {}
class TextReader_iPad : TextReader_Shared {}
class TextReader_iPhone : TextReader_Shared {}
/////
Now I want Reader to have iPad/iPhone specifics. In the WPF/Silverlight land I could solve this
with partial classes. To be fair it was all solved at compile time. Basically have 3 directores:
Shared, WPF, Silverlight. Then one build would do the partial classes of Shared+WPF and the
other was Shared+Silverlight.
For iOS this would need to be a runtime thing. Picking up the right Reader base class.
////
class Reader_Shared : NSObject {}
class Reader_iPad : Reader_Shared {}
class Reader_iPhone : Reader_iPad {}
Now what would the PDFReader_Shared and TextReader_Shared derive from? It would need to be change
at runtime I guess which is scary (not sure if it's possible?)
@SlaunchaMan
Copy link

You could implement a class cluster. You’d only expose the @interface for the main class in the public header. The implementation file would look like this:

@interface iPhoneClass : MyClass

// iPhone methods defined here

@end

@implementation iPhoneClass

// iPhone methods defined here

@end

@interface iPadClass : MyClass

// iPad methods defined here

@end

@implementation iPadClass

// iPad methods implemented here

@end


@implementation MyClass

+ (id)alloc
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        return [iPadClass alloc];
    }
    else {
        return [iPhoneClass alloc];
    }
}

// Shared methods go here

@end

If you don’t add any instance variables to iPhoneClass or iPadClass, you can skip implementing alloc, as their memory layout will be equivalent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment