开发者

Keeping track of touched points in mutable array

开发者 https://www.devze.com 2023-03-10 08:23 出处:网络
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?\"

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,* and drawn is never created. From the Resource Management Guide:

In iOS, any object that conforms to the NSCoding protocol is initialized using the initWithCoder: method. This includes all subclasses of UIView[...] Custom views in iOS do not use the initWithFrame: method for initialization.

The value at drawn is therefore nil, and calling [nil count] gives 0; [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 the if block.

When you create an NSMutableArray using alloc/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, self will be invalid (nil), and using one of its properties will likewise be incorrect. That's the purpose of if(self). You should do this instead:

if(self){
    self.drawn = [NSMutableArray array];
}

This creates an autoreleased NSMutableArray which your view then properly retains.


*I wish I knew why too. It does get used in OS X.


I would check if the

- (id)initWithFrame:(CGRect)frame

is called.

0

精彩评论

暂无评论...
验证码 换一张
取 消