0

I am programming an iPhone game which has items laid out on a grid. Each item is represented by an object, and I want to use a 2D array to represent the contents of the grid. Since I will need to be passing the array through methods, I have attempted to declare it as:

MyClass*** grid;

and have a method to return it as:

-(MyClass ***) {
    return grid
}

But before even compiling i get this error:

Pointer to non-const type 'MyClass *' with no explicit ownership.

What does this mean, and why would it happen?

7
  • Are you using automatic reference counting? Commented Nov 19, 2011 at 21:54
  • ARC requires explicit ownership. Pointers to object pointers have unknown owners, so it won't work. See stackoverflow.com/q/7804435 which is similar. Commented Nov 19, 2011 at 22:08
  • The suggested answer on that question is to store the NSError** as a simple pointer. However, that is not an option here (I believe). Could you suggest another alternative? Commented Nov 19, 2011 at 22:11
  • You could use manual reference counting, or you can use nested NSArrays. If the number of elements in your C-array is known at compile time, you can declare the array as MyClass *grid[20][20] and it should work. Commented Nov 19, 2011 at 22:17
  • But I need to pass it. I was under the impression that passing arrays was forbidden, and to do so you were required to pass a pointer instead. Commented Nov 19, 2011 at 22:21

2 Answers 2

1

When using Automatic Reference Counting you cannot have pointers to object pointers that way, since the owner will be unknown.

You can use nested NSArray objects instead, or switch to manual reference counting (you shouldn't do the latter if you already have a large project).


You could also instead have a method like this which the callee will call multiple times (once for each cell in the grid):

- (id)itemAtX:(NSUInteger)x y:(NSUInteger)y {
  // TODO: Add bounds checking.
  return grid[x][y];
}
Sign up to request clarification or add additional context in comments.

2 Comments

I dont' know about using an NSArray, since I'm attempting to represent a grid of data with it, and NSArrays are dynamically sized. I suppose I could set the objects that I wanted to be filled to nil.
I'd recommend using NSNull object instead
1

You could just use the standard C 2D array for this,

MyClass *item = (MyClass *)grid[x][y];

3 Comments

How would I then go about passing/returning grid from a method?
Remember that objective C is a superset of C, so you can pass C around as you wish. Take a look at borkwarellc.wordpress.com/2007/09/06/…
So, in answer to your question: - (MyClass *)returnGrid:(MyClass *) grid { // do something to the grid... return grid }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.