简体   繁体   English

NSArray来自视图控制器中的子类v.NSArray

[英]NSArray from subclass v. NSArray in view controller

I have two classes: GHHaiku and GHViewController . 我有两个类: GHHaikuGHViewController In GHHaiku , I declare @property (nonatomic, strong) NSArray *arrayAfterFiltering; GHHaiku ,我宣布GHHaiku @property (nonatomic, strong) NSArray *arrayAfterFiltering; .

In GHViewController I instantiate GHHaiku as @property (nonatomic, strong) GHHaiku *ghhaiku; GHViewController我将GHHaiku实例GHHaiku @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. 这里的NSLog产生正确的计数,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. NSLog产生的计数为0。

Why is this any different? 为什么这有什么不同?

The problem is when you say that you instantiate @property (nonatomic, strong) GHHaiku *ghhaiku . 问题是当你说你实例化@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. 所以self.ghhaiku是零,你在第二个例子中毫无结果地发送消息给nil。

尝试进行分配

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM