当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Creating Custom Control - DataSource is nil

问题描述:


I'm trying to create a custom control based on UIScrollView.

The control should get the information necessary through its dataSource object (same behaviour as UITableView or UIPickerView).

The problem is that I'm trying to define the dataSource through Interface Builder and not by code. (ex. you can set a UITableView dataSource to File's owner in a .xib file)

Here's my new control header:

#import <UIKit/UIKit.h>

@protocol HorizontalPickerDataSource;

@interface HorizontalPicker : UIScrollView

@property (nonatomic,assign) IBOutlet id <HorizontalPickerDataSource> dataSource;

@end

@protocol HorizontalPickerDataSource

- (NSInteger)numberOfColumnsInHorizontalPicker:(HorizontalPicker *)horizontalPicker;

- (UIView *)horizontalPicker:(HorizontalPicker *)horizontalPicker viewForColumn:(NSInteger)column;

@end

Pretty straightforward.

The UIViewController that adopts the HorizontalPicker should be its dataSource.

I'm defining it through Interface Builder since I set the dataSource an IBOutlet.

I override initWtihCoder and logged the dataSource there (after creating the object of course) and it appears to be nil.

- (id)initWithCoder:(NSCoder *)aDecoder

{

self = [super initWithCoder:aDecoder];

if(self){

NSLog(@"dataSource: %@",self.dataSource);

[self setup];

}

return self;

}

the setup method whole logic based on dataSource not being nil.

Why is dataSource nil and how can I fix it?

Thank you for your time (:

Edit #1

Here's my implementation of NSCoding, what's wrong with it?

- (id)initWithCoder:(NSCoder *)aDecoder

{

id dataSource = [aDecoder decodeObjectForKey:@"dataSource"];

self = [super initWithCoder:aDecoder];

if(self){

self.dataSource = dataSource;

NSLog(@"dataSource: %@",self.dataSource);

[self setup];

}

return self;

}

- (void)encodeWithCoder:(NSCoder *)aCoder

{

[super encodeWithCoder:aCoder];

[aCoder encodeObject:self.dataSource forKey:@"dataSource"];

}

网友答案:

You have to completely implement NSCoding for this to work. In your case, your initWithCoder: is not decoding the datasource. You need to do something like this:

- (id)initWithCoder:(NSCoder *)aDecoder {
     id ds = [decoder decodeObjectForKey:@"dataSource"];
     if(self = [self initWithDataSource:ds){
         NSLog(@"dataSource: %@",self.dataSource);
         [self setup];
     }
     return self;
 }

You should also provide the companion method in NSCoding, encodeWithCoder:.

分享给朋友:
您可能感兴趣的文章:
随机阅读: