This question might be off base, but here's the problem I'm having:

I'm trying to run an example from the iPhone SDK, and I'm running into an access violation. I've traced down some behaviour that I think is suspicious.

Here's what the class looks like:

@interface TableViewCell : UITableViewCell {

    UILabel *_earthquakeLocationLabel;
    UILabel *_earthquakeDateLabel;
    UILabel *_earthquakeMagnitudeLabel;
    UIImageView *_magnitudeImageView;

When I set a breakpoint in

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier

And look at "self" in the debugger, it shows that _earthquakeDateLabel is "0x12", _earthquakeMagnitudeLabel is 0x1000, and the other two are zero. If I try to assign to either of the nonzero ones, I get an access violation.

I'm guessing what's happening is that these have bogus values in them, and when I try to assign to them, that tries to decrement a reference on the bogus value and blows up. But as I said, I'm fairly new to Objective C, so I may be off base.

So my question is, is there anything special about initializing these values that I should be doing? Or any way to assign to the value when it has a bogus value in it?

Some additional information:

So if I assign nil to _earthquakeDateLabel and _earthquakeMagnitudeLabel in initialize, that fixes the problem. But I don't understand why the object is created with values in those fields; I expect them to be nil. The object is being created on the heap:

TableViewCell *cell = [[[TableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];

No correct solution


It sounds like the self pointer is bogus. The values 0x12 and 0x1000 are integer constants; they're definitely NOT pointers to valid memory addresses. The fact that you are seeing those values indicates that something is wrong, and attempting to manipulate them in any way (reading or writing them) will result in badness. In this case, you're getting an access violation because you're trying to write to memory addresses 0x12 and 0x1000, which are invalid addresses.

How are you creating the TableViewCell objects? Are you doing TableViewCell *myCell = [[TableViewCell alloc] initWithFrame:...]? That is the correct way.

Now I'm going to invoke my psychic debugger: my guess is that you're forgetting to declare your TableViewCell object with a pointer, i.e. you're declaring it as TableViewCell myCell instead of TableViewCell *myCell (note the presence of the asterisk). This will create the object on the stack instead of the heap, and as a result, it will have garbage in its data members, instead of zeros. Objective-C objects, when properly allocated, will have all of their data members initialized to 0 (or NULL, nil or false, depending on the data type) after a successful call to alloc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow