开发者

How to populate a stack with objects of various types

开发者 https://www.devze.com 2023-02-17 02:06 出处:网络
Using an NSMutableArray ivar, I plan to write a class that acts like a stack and which objects of various types should be able to be retrieved from.

Using an NSMutableArray ivar, I plan to write a class that acts like a stack and which objects of various types should be able to be retrieved from.

Whenever that stack threatens to run out of objects because almost all have yet been retrieved, it should automatically push new objects onto itself by fetching them from some sort of as-generic-as-possible "object emitter". For example, there should be supplicant classes which return instances of NSImages or of NSString or any other imaginable types which should be put on the stack but each have to be treated in a separate way beforehand.

What would be the easiest pattern of "plugging in" those object emitting classes into my stack class? The stack class should not need to be aware of the object types it has to deal with, this is where some "helper classes" might set it - but I have no clue wh开发者_StackOverflowere their place would be. I tried Dynamic Creation using NSClassFromString but that just doesn't feel quite right.


NSMutableArray is capable of storing any object. Unlike generic collections in Java, where data structures store instances of specific classes, Cocoa allows you to add anything to an NSArray. So, your pop method could simply remove the last object of the array, check to see if the size is smaller than some threshold, and then request new objects from supplier classes.

For example:

- (NSObject *)pop {
      NSObject *poppedObject = [mutableArray lastObject];
      [mutableArray removeLastObject];
      if ([mutableArray count] < SMALLEST_ALLOWABLE_STACK_SIZE) {
          for (MYContentProvider *provider in [self contentProviders]) {
               [mutableArray addObjectsFromArray:[provider fetchContent]];
          }
      }
      return poppedObject;
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消