1

我在设计我的应用程序时遇到了一些结构性困境。我想使用一系列嵌套循环来创建大量自定义对象。创建这些对象后,我想将它们全部存储到一个对象中,该对象是这些对象的集合。

可视化:

@interface CollectionOfObjectA : NSObject
@property (nonatomic, strong) NSArray *reference;
@end
@implementation CollectionOfObjectA
-(CollectionOfObjectA *)init{
    NSMutableArray *ref = [[NSMutableArray alloc] init];
    for(int i=0; i < largeNumber; i++){ // There will be nested loops.
        NSString *str = @"string made from each loop index";
        ObjA *obj = [[ObjA alloc] initWithIndexes: str]; 
        [ref addObject: obj];
    }
    self.reference = [ref copy];
}
@end

@interface ObjA : CollectionOfObjA
// several properties
@end
@implementation ObjA
-(ObjA *)initWithIndexes:(NSString *)indexes{
    self = [super init];
    // Use passed indexes to create several properties for this object.
    return self;
 }
 @end

创建这个作为子对象集合的对象的最佳方法是什么?我让 ObjA 成为 CollectionOfObjectA 的孩子是不正确的——应该反过来吗?任何帮助将不胜感激。

4

1 回答 1

1

好的,我的建议:我有近 30 个自定义对象。比如事件。之后,我制作Factory了可以创建所有这些的课程。而且这个类Factory也有方法:getAllObjects

像这样:

#include "CustomEvent.h"
@interface EventFactory

+(NSArray*)allEvents;

@end

@implementation EventFactory

-(CustomEvent*)firstEvent{/*something here*/}
-(CustomEvent*)secondEvent{/*yes, you should init custom object here*/}
-(CustomEvent*)thirdEvent{/*and after that you can put them*/}
/*
...
*/
+(NSArray*)allEvents{
      EventFactory* factory = [[EventFactory alloc]init];
      return @[
               [factory firstEvent],
               [factory secondEvent],
               /*...*/
               [factory lastEvent]
               ];

}
@end

我回到这里NSArray是因为我不需要,实际上,知道他们的任何东西。他们已经有了处理程序,并且订阅了自定义通知。您可以返回NSDictionary以获得更好的访问权限。

PS:为了更好的解释,您可以阅读 wiki 中有关工厂模式的文章

但是,如果你想更好地操作对象,你应该使用其他模式:复合模式

我的意思是说?

@interface EventCollection{
   NSMutableArray* YourArray;
}

-(void)addCustomEvent:(CustomEvent*)event atPosition:(NSInteger)position;
-(void)removeCustomEventAtPosition:(NSInteger)position;
-(void)seeAllEvents;
-(void)seeAllPositions; /*if you want*/
-(void)doesThisPositionAvailable:(NSInteger)position;

@end

@implementation EventCollection

-(void)addCustomEvent:(CustomEvent*)event atPosition:(NSInteger)position{
   /*maybe you should check if this position available*/
   if ([self doesThisPositionAvailable:position]){
        /*add element and save position*/
   }
}

-(void)removeCustomEventAtPosition:(NSInteger)position{
    if (![self doesThisPositionAvailable:position]){
          /*destroy element here*/
    }
}

-(void)seeAllEvents{
    /*yes, this method is the main method, you must store somewhere your objects.
      you can use everything, what you want, but don't share your realization.
      maybe, you want use array, so, put it as hidden variable. and init at the initialization of your collection
    */
    for (CustomEvent* event in YourArray){
         [event description];
    }
}

@end
于 2013-05-11T09:09:46.893 回答