Search code examples
objective-cnsarrayrealm

NSArray create with some elements plus another NSArray


I am trying to use model inheritance on . So I minded up using the code below to override and also call super method.

+ (NSArray *)requiredProperties {
    return @[[super requiredProperties], @"thisIsRequired",@"thisIsAlsoRequired"];
}

So the question: is it OK to create an NSArray on the fly while also using another NSArray and some more elements:

NSArray *mySecondArray = @[myFirstArray, @"andSomeExtras", @"alsoMoreExtras"];

What I have been expecting is; first element of mySecondArray should be the first element of myFirstArray. Second element of mySecondArray should be the second element of myFirstArray and so on. (size of myFirstArray) +1 th element of mySecondArray should be @"thisIsRequired" .

Or I am making up some kind of magix?

Well, as you can see I am new to the stuff and I might be confused.


Solution

  • In general, it is okay to instantiate such heterogeneous arrays with Foundation. It's just not what you want here. In your example, you would end up with the following instead:

    NSArray *myFirstArray = @[@"firstsFirstsElement", @"firstsSecondElement"];
    NSArray *mySecondArray = @[myFirstArray, @"andSomeExtras", @"alsoMoreExtras"];
    /* => 
    @[
      @[@"firstsFirstsElement", @"firstsSecondElement"],
      @"andSomeExtras",
      @"alsoMoreExtras",
    ]
    */
    

    You're looking for - arrayByAddingObjectsFromArray:. You can use it like seen below:

    + (NSArray *)requiredProperties {
        return [super.requiredProperties arrayByAddingObjectsFromArray:@[
             @"thisIsRequired",
             @"thisIsAlsoRequired",
        ]];
    }