Joel Derfner
Joel Derfner

Reputation: 2207

NSArray from subclass v. NSArray in view controller

I have two classes: GHHaiku and GHViewController. In GHHaiku, I declare @property (nonatomic, strong) NSArray *arrayAfterFiltering;.

In GHViewController I instantiate GHHaiku as @property (nonatomic, strong) GHHaiku *ghhaiku; and then follow it later with this code:

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category == %@", cat];
        NSArray *filteredArray = [self.haiku filteredArrayUsingPredicate:predicate];  //haiku is an NSMutableArray property of `GHViewController`
        NSLog(@"%d",filteredArray.count);

The NSLog here produces the correct count, 116.

But when I use the following code,

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category == %@", cat];
        self.ghhaiku.arrayAfterFiltering = [self.haiku filteredArrayUsingPredicate:predicate];
        NSLog(@"%d",self.ghhaiku.arrayAfterFiltering.count);

the NSLog produces a count of 0.

Why is this any different?

Upvotes: 0

Views: 60

Answers (2)

Neo
Neo

Reputation: 2807

Try doing the allocation

self.ghhaiku.arrayAfterFiltering =[[NSArray alloc] initWithArray: [self.haiku filteredArrayUsingPredicate:predicate]];

Upvotes: 0

matt
matt

Reputation: 536027

The problem is when you say that you instantiate @property (nonatomic, strong) GHHaiku *ghhaiku. You don't. All you do there is declare the property. So you have a property but the property has no value; it is nil. So self.ghhaiku is nil and you are fruitlessly sending messages to nil in your second example.

Upvotes: 2

Related Questions