Anthony Main
Anthony Main

Reputation: 6068

Child array always empty

Using the following code I am always getting category.subCategories count to be 0 using the Xcode debugger

Category *category = [[Category alloc] init];
category.title = @"Pubs & Bars";
category.icon = @"cat_pubs&bars";
category.subCategories == [[NSMutableArray alloc] init];

Category *subCategory = [[Category alloc] init];
subCategory.title = @"Test Sub Category 1";

[category.subCategories addObject:subCategory];

The object defined using the following code:

@interface Category : NSObject {
    NSInteger *categoryId;
    NSMutableString *title;
    NSString *icon;
    NSMutableArray *subCategories;
}

@property(assign,nonatomic,readonly) NSInteger *categoryId;
@property(nonatomic,copy) NSMutableString *title;
@property(nonatomic,copy) NSString *icon;
@property(nonatomic,retain) NSMutableArray *subCategories;

@end

Upvotes: 1

Views: 130

Answers (1)

gcamp
gcamp

Reputation: 14672

In the following line, category.subCategories == [[NSMutableArray alloc] init];, you have a double equal and that check if it's true. So subCategories is still nil here, that's why you have a count of 0.

Use category.subCategories = [[NSMutableArray alloc] init]; instead.

Personally, I would use a custom getter to lazily create an NSMutableArray. In Category.m :

- (NSMutableArray*) subCategories {
   if (subCategories == nil) {
      subCategories = [[NSMutableArray alloc] init];
   }
   return subCategories;
}

That way, you just need to use subCategories as it is already existent, since it will be created on demand. That way, you also no more have a leak.

Upvotes: 7

Related Questions