UPDATE: I realized that the “initWithFrame” method is never called, so I placed my array’s init elsewhere. Thanks for reading. (for anyone, what’s the point of initWithFrame if it is not called?”
I’ve been staring at this code for about an hour and am probably missing a simple and obvious issue. I’m merely trying to keep an array of touched points. My UIView’s init says this:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
self.drawn=[[NSMutableArray alloc] init ];
return self;
}
Then I have this in another method:
CGPoint point=[[touches anyObject] locationInView:self];
NSLog(@"touched point: %f, %f",point.x,point.y);
[self.drawn addObject:[NSValue valueWithCGPoint:point]];
The NSLog confirms that “point” exists and contains x and y data.
Why then does my “drawn” array never get anything? I have read the NSValue tutorials and I seem to be doing this correctly. An NSLog of [self.drawn count] always shows 0 despite that this code has triggered.
And of course “drawn” is also an ivar of my custom UIView, properly synthesized also.
Your
initWithFrame:never gets called,* anddrawnis never created. From the Resource Management Guide:The value at
drawnis thereforenil, and calling[nil count]gives0;[nil addObject:]similarly does nothing.That said, your
initWithFrame:also has two memory problems. Your assignment to the property over-retains the array, and you should be doing that assignment inside theifblock.When you create an
NSMutableArrayusingalloc/init, you own that array. When you then assign it using a property which is defined as retaining, you have an extra claim on that object, which can eventually cause a leak.Second: if, for whatever reason, the call to
[super initWithFrame:frame]fails,selfwill be invalid (nil), and using one of its properties will likewise be incorrect. That’s the purpose ofif(self).You should do this instead:
This creates an autoreleased
NSMutableArraywhich your view then properly retains.*I wish I knew why too. It does get used in OS X.