質問

I have a UITableViewController :

#import <UIKit/UIKit.h>
#import "MainClass.h"
@interface MainViewController : UITableViewController
@property (strong, nonatomic) MainClass *mainClass;
@end

And a class that i want to use as a data source for the table view:

@interface Domain : NSObject <UITableViewDataSource>

-(id) initWithName: (NSString*)name;

@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSMutableArray* list;

@end

When i want to simply test if it's working i create a local domain and i add some documents in it:

Domain* domain = [[Domain alloc] init];
Document* document1 = [[Document alloc]initWithName:@"test1"];
[domain.list addObject:document1];

And then i declare the domain as a data source ( i overrides the two required methods) :

self.tableView.dataSource = domain;

Unfortunately, this cause a Bad access exception. I guess it's because the local variables are released too soon. I'm guessing this because when i declare both domain and document as property, it works just fine. Can anyone explain me the reason of this too soon release and how to avoid it?

役に立ちましたか?

解決 2

Create strong reference to domain, for example:

@property (strong, nonatomic) Domain* domain;

And change allocation of your domain object to:

self.domain = [[Domain alloc] init];
Document* document1 = [[Document alloc]initWithName:@"test1"];
[self.domain.list addObject:document1];

and after that:

self.tableView.dataSource = self.domain;

他のヒント

'dataSource' is a weak property, so you must keep another reference to the object for it not to be released.

Therefore defining a property on the view controller is really the best solution.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top