Creating an array that contains only objects of a given class

前端 未结 3 1273
一整个雨季
一整个雨季 2021-01-23 15:12

Ok, so I have the code below (Objective-C FYI) and I was wondering if I want to create an NSMutableArray of c_data objects, how would I go about doing that? It\'s s

相关标签:
3条回答
  • 2021-01-23 15:53

    You would create an NSMutableArray and insert c_data objects into it.

    0 讨论(0)
  • 2021-01-23 16:01

    There is no such thing as statically typed / template / generic collections in Objective-C. Basically, the point of a strongly-typed collection is to provide static type safety at compile time. Such an approach makes little sense in a language as dynamic as Objective-C. The approach to the problem of disparate object types in Objective-C collections is to only insert the appropriate object type(s). (Also, remember that the array will retain objects it contains, so if you insert a new object without releasing and you lose the pointer to it, you're leaking memory.)

    If you think about it, one of the biggest benefits to generics is being able to retrieve objects from the collection directly into a statically-typed variable without casting. In Objective-C, you can just store to an id variable and send whatever message you like without fretting about a ClassCastException, or the compiler complaining that an object doesn't (may not?) implement the method you're attempting to invoke. You can still statically type variables and cast results if desired, but the easier approach is to use dynamic typing (and -isKindOfClass: and -respondsToSelector: if necessary).

    Incidentally, there are several related incarnations of this question on Stack Overflow. Knowing the term(s) to search for ("generic", "strongly-typed", or "template") can help find them. Here are a few:

    • Why do C# and VB have Generics? What benefit do they provide?
    • Is there any way to enforce typing on NSArray, NSMutableArray, etc.?
    • Is there anything like a generic list in Cocoa / Objective-C?
    • Are there strongly typed collections in Objective-C?

    Finally, I agree with William — your init methods are pretty egregious in the sample you provided. You'd do well to learn and heed Apple's rules of Allocating and Initializing Objects in Objective-C. It requires breaking habits from other languages, but it will save you endless hours of insanity at some point down the road. :-)

    0 讨论(0)
  • 2021-01-23 16:08
    [NSMutableArray addObject:[[[c_data alloc] init] autorelease]];
    

    Objective-C arrays aren't typed. It seems you have some C++ unlearning to do.

    On a related note, your inits are pretty bad. You need to call super init as well, as such:

    - (id)init {
      self = [super init];
      if (self != nil) {
        //Initialize here.
      }
      return self;
    }
    
    0 讨论(0)
提交回复
热议问题