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) NSStri开发者_如何学Gong *icon;
@property(nonatomic,retain) NSMutableArray *subCategories;
@end
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.
精彩评论