0

Whilst learning Objective-C I ran into a situation where I needed to add two different objects (one inherits from the other) to an array. Whilst it does work I was not 100% sure it was good practice?

@interface TireBasic : NSObject {
}
@end

@interface TireSnow : TireBasic {
}
@end

// To this array?
TireBasic *tires[4];

cheers -gary-

2
  • 1
    Because NSArray is not always the best solution? In many cases it's a better choice, but there's nothing wrong with using plain C arrays when efficiency and speed is important. Commented Sep 22, 2009 at 17:37
  • Thanks, I will have a look at using NSArray tomorrow. Commented Sep 22, 2009 at 17:38

4 Answers 4

1

Looks good. Another option would be to use the id type.

Sign up to request clarification or add additional context in comments.

1 Comment

I did quickly try using the id type earlier but I got mixed up somewhere. Like I say I will do a smaller testBed program tomorrow to get it working in isolation.
1

There's nothing wrong with that. Basic polymorphism at work here.

Comments

0

Arrays are not typed in Objective-C so you can have any type of object as an array element. As to whether it is good practice or not, it depends entirely on how your planning on using the array

Comments

0

I fail to see why NSArray could not be used here. NSArray can contain multiple object types.

2 Comments

Hi Jasconius, the plainC array was just where I ended up with my little test. I will as you and a few other have suggested have a look at NSArray and id. Many thanks ...
An NSArray can often be unnecessary overhead especially when your arrays are as small as 4 elements. It does provide some nifty features for enumeration and value checking, but if those aren't required then a plain C array will often suffice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.