Objective-C - Factory to return a given class type?

With generics in languages ​​like C # or Java, can you have a factory that returns a result based on a given type? For example, you can return a factory method:

Book
List<Book>
Door
List<Door>

      

Is it possible to achieve the same result with objective-c? Can I somehow tell the generateObjects

method to return me an array of books?

[self getDataFromWeb:@"SOME_URL" andReturnResultWithType:[Book class]];
// What about an array of Books?

- (id)getDataFromWeb:(NSString*)url andReturnResultWithType:(Class)class
{
    // Convert JSON and return result
    // Mapping conversion is a class method under each contract (Book, Door, etc)
} 

      

Let's say this is one of my data contracts

@interface Book : JSONContract

@end

@implementation Book

+ (NSDictionary *)dataMapping
{
   // returns an NSDictionary with key values
   // key values define how JSON is converted to Objects
}

@end

      

EDIT:

The modified examples are clearer

+3


source to share


2 answers


No, you can't say that your array will contain a String. But, yes, you can create a String based on a class definition or even a class name.

Objective-C as "reflection" like Java, it's called "introspection"

For example, you can create an object based on its class name using this code

NSString* myString = (NSString*)[[NSClassFromString(@"NSString") alloc] init];

      



NSClassFromString is documented here: https://developer.apple.com/library/mac/#documentation/cocoa/reference/foundation/miscellaneous/foundation_functions/reference/reference.html

If you want the compiler to check the types for you, you can also use the Class object directly as this

Class stringClass = [NSString class];
NSString* myString = [[stringClass alloc] init];

      

+4


source


Yes, NSArray and NSMutableArray both store objects of type id, which means you can put whatever you want in there and return it to the user. You are just checking the passed parameter to branch your logic to generate the objects that you put into the array.



Does your comment suggest this is for JSON conversion? To convert to JSON, you must have a set of conditions that check if the value is a number, a string, etc. So you can add a condition that says that if the class parameter is an NSString class, then just assume the JSON value is a string.

+1


source







All Articles