0

I have the following code that tries to set up a GridView and I have a GridviewController subclass that manages the datasource. This is the code that is used to set it up.

            AQGridView* gridView = [[AQGridView alloc] initWithFrame:frame];
            NUBMyCpGridviewController* controller = [[NUBMyCpGridviewController alloc] init];
            gridView.dataSource = controller;
            gridView.delegate = controller;
            [gridView reloadData];

However, the app crashes when it tries to access the datasource. This is the line (in the Gridview class) that gives the tries to call the method and crashes it:

AQGridViewCell * cell = [_dataSource gridView: self cellForItemAtIndex: index];

The error is exc_bad_access. What could be the problem? Is it because the object is being released too early? How can I rectify it?

nubela
  • 1
  • 24
  • 75
  • 123

1 Answers1

0

You're right; the problem is most likely that your NUBMyCpGridviewController is being deallocated. Based on your code snippet it looks like no one is retaining it.

My suggestion would be to make it a strong @property of whichever class your snippet code is being executed in.

yuji
  • 16,695
  • 4
  • 63
  • 64
  • I'm using ARC. How do I do that? Do I add a strong property to the class or to the object? Do I have to do it in the header file? – nubela Mar 07 '12 at 13:42
  • Whether or not you're using ARC, just put `@property (strong) NUBMyCpGridviewController* controller;` in your .h, `@synthesize controller;` in your .m, and then just use `self.controller` in your code above instead of `controller`. – yuji Mar 07 '12 at 13:46
  • P.S. If you're asking questions like that, you should probably go and read some of Apple's basic tutorials on Objective-C and Cocoa when you get a chance. – yuji Mar 07 '12 at 13:55
  • i know about that, but do i have to declare all strong objects like that? this is my grief with obj c. its retardedly annoying. and i dont even get free private methods. – nubela Mar 07 '12 at 14:50
  • I'm not completely sure what you're asking, but if you don't want the object to be deallocated, then someone is going to have to own it. That means that something will need to have a strong reference to it. It doesn't necessarily have to be a `@property`: it could be inside a container that someone else is retaining (since containers retain their elements), for example. But if no one owns an object, it's not going to stick around. – yuji Mar 07 '12 at 15:04