简体   繁体   中英

subclassing UIViewController in iOS

I got confused on subclassing a UIViewController in iOS, I have a parent viewcontroller which conforms the UICollectionViewDataSource protocol (in its private interface inside the implementation file).

/* Parent.m */

@interface Parent () <UICollectionViewDataSource>

// this CollectionView is connected to storyboard
@property (weak, nonatomic) IBOutlet UICollectionView *CollectionView;

@end


@implementation Parent


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.somecount;
}

@end

And then I create a child view controller which inherited from parent. The child knows nothing about UICollectionViewDataSource as the datasource implemented in parent's private interface.

/* child.h */

@interface child : parent
// nothing was mentioned here that parent has a method to set the count using 'somecount'
@end

Then I set the viewcontroller from mainstoryboard as the child view controller.

how come ios get the value from parent's property 'somecount' and set the value for child?

thanks.

You ask:

how come ios get the value from parent's property somecount and set the value for child?

A subclass always inherits the properties and methods of its super class. They may or may not be public interfaces (you haven't shown us the declaration of somecount , so we don't know), but regardless, they are there and will be resolved at runtime (unless you override those methods/properties in the child , which you don't appear to be doing). If there are private methods and properties in parent , you might not be visible at compile-time from the child , but they're still there and will behave properly at runtime.

So, when the scene with the collection view specifies the child as the data source for the collection view, if child doesn't implement those UICollectionViewDataSource methods, it will automatically end up invoking those of the parent . Likewise, when any of those methods refer to somecount , if the child doesn't override it, it again will end up calling the appropriate accessor methods of the parent . Bottom line, child automatically inherits all of the behaviors, methods, and properties of the parent .

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