从父级初始化子对象

时间:2013-05-11 08:59:00

标签: objective-c inheritance

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

可视化:

@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的孩子 - 它应该是相反的吗?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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以获得更好的访问权限。

P.S:为了更好的解释,你可以阅读wiki关于Factory pattern

的文章

但是,如果你想更好地操纵对象,你应该使用其他模式:Composite pattern

我的意思是什么?

@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