简体   繁体   中英

Count method of subclass of NSMutableArray crashes app

This seems to be a common problem, but I can't figure out anything from the answers I've seen so far. I have an iPhone app that uses a subclass of NSMutableArray to store objects, plus some additional properties. The subclass is skhCustomArray . The subclass initializes fine, with no objects in the skhCustomArray , and I assign it to the the property of my view controller, which is a pointer to an skhCustomArray .

    prescriptionListVC* newPrescList = [[prescriptionListVC alloc] initWithNibName:@"PrescriptionList" bundle:nil];
    newPrescList.curPersonPrescriptions = [personDetails objectAtIndex:0];

That works fine. Yet when I push my view managed by my view controller onto the navigation controller stack, the count method in the numberOfRowsInSection method crashes the app, see below.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [curPersonPrescriptions count];

}

What could be causing this? How can a valid custom array, with no objects, not return a valid count? Where am I going wrong? Thanks.

Subclass of NSArray? You're aware that NSArray is a class cluster , and is therefore somewhat difficult to subclass, right? In fact, it's so fraught with danger that the NSArray documentation has a whole section dedicated to what you need to do in order to subclass it .

I'll bet that that's the source of your woes.

When you subclass NSMutableArray, you need to implement some mandatory methods like count, addObject:, insertObjectAtIndex etc. This is what we call as class cluster.

If you want to add some more feature/behavior to already implemented object then you can write a "category" instead of "subclassing" it.

If you want to subclass it, then you have to implement all those methods which your are going to use so better write a category of NSMutableArray and extend the feature what you want and use the NSMutableArray object only. This will solve your problem and also this is the easy and almost right way to add new behavior to already existing class.

You almost certainly don't need to subclass NSMutableArray in this situation. Instead, make a new class which has an array as a property , along with the extra properties you desire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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