Search code examples
objective-cxcodecocoansoutlineview

NSOutlineView displays three levels


I am using NSOutlineView and i want to display the fourth sub level. Now i am able to display only three sub levels.

outlineViewController.m

 -(id)init{
     self = [super init];
     if(self){
         _people = [[NSMutableArray alloc]init];

         Person *quick = [[Person alloc]initWithName:@"First"];
         [quick addChild:[[Person alloc]initWithName:@"Second"]];
         [(Person *)[quick.children objectAtIndex:0]addChild:[[Person alloc]initWithName:@"Third"]];

         [_people addObject:quick];

     }
     return self; 
 }

person.m

-(id)init{
     return [self initWithName:@"Name"]; 
 }


 -(id)initWithName:(NSString *)name {
         self = [super init];
         if(self){
             _name = [name copy];
             _children = [[NSMutableArray alloc]init];

         }
         return self; 
     }

 -(void)addChild:(Person *)p {
     [_children addObject:p];
 }

person.h

 @property (copy)NSString *name;
 @property(readonly,copy)NSMutableArray *children;
 -(id)initWithName:(NSString *)name;
 -(void)addChild:(Person *)p;

I am getting the output something like this.

>First
   >Second
      Third

I want Output like this..

>First
   >Second
      >Third
         >Fourth
            Fifth

Thank you.


Solution

  • You are adding a child to second here:

    [(Person *)[quick.children objectAtIndex:0]addChild:[[Person alloc]initWithName:@"Third"]];
    

    Similarly you may add child to third as:

    [(Person*)[((Person *)[quick.children objectAtIndex:0]).children objectAtIndex:0]addChild:[[Person alloc]initWithName:@"Fourth"]];
    

    and then to fourth as:

     [(Person*)[((Person*)[((Person *)[quick.children objectAtIndex:0]).children objectAtIndex:0]).children objectAtIndex:0] addChild:[[Person alloc]initWithName:@"Fifth"]];
    

    OR to make it simple, first create the lowest level object and then add it as a child to its parent:

    Person *fifth = [[Person alloc]initWithName:@"Fifth"]; 
    Person *fourth = [[Person alloc]initWithName:@"Fourth"];
    [fourth addChild: fifth];
    Person *third = [[Person alloc]initWithName:@"Third"];
    [third addChild: fourth];
    Person *second = [[Person alloc]initWithName:@"Second"];
    [second addChild: third];
    Person *quick = [[Person alloc]initWithName:@"First"];
    [quick addChild: second];