将临时对象添加到 NSMutableArray
我有一个自定义类 MDRect,我试图添加一个 NSMutableArray
数组是一个属性:
@property (retain) NSMutableArray* array;
它在 NSView 子类的 initMethod 中初始化:
-(id)init {
array = [NSMutableArray new];
return [super init];
}
然后我尝试在此处的数组中添加一个对象:
-(void)mouseUp:(NSEvent *)theEvent
{
NSPoint mouseLoc = [NSEvent mouseLocation];
mouseLoc = [self mouse:mouseLoc inRect:[self frame]];
CGSize temp;
NSLog(@"%f",mouseLoc.y - mouseLocation.y);
NSLog(@"%f",mouseLoc.x - mouseLocation.x);
temp.height = mouseLoc.y - mouseLocation.y;
temp.width = mouseLoc.x - mouseLocation.x;
tempRect.size = temp;
MDRect * rect = [[MDRect alloc] initWithColor:[NSColor orangeColor] andRect:tempRect];
[array addObject:rect];
int i = (int)array.count;
NSLog(@"%i",i);
[self setNeedsDisplay:YES];
}
但该对象不是被添加到数组中。它在 NSLog 函数中从不返回除 0 之外的任何值。我做错了什么?
I have a custom class MDRect that i am trying to add an NSMutableArray
the array is a property:
@property (retain) NSMutableArray* array;
it is initialized in the initMethod of the NSView subclass:
-(id)init {
array = [NSMutableArray new];
return [super init];
}
then i am trying to add an object in the array here:
-(void)mouseUp:(NSEvent *)theEvent
{
NSPoint mouseLoc = [NSEvent mouseLocation];
mouseLoc = [self mouse:mouseLoc inRect:[self frame]];
CGSize temp;
NSLog(@"%f",mouseLoc.y - mouseLocation.y);
NSLog(@"%f",mouseLoc.x - mouseLocation.x);
temp.height = mouseLoc.y - mouseLocation.y;
temp.width = mouseLoc.x - mouseLocation.x;
tempRect.size = temp;
MDRect * rect = [[MDRect alloc] initWithColor:[NSColor orangeColor] andRect:tempRect];
[array addObject:rect];
int i = (int)array.count;
NSLog(@"%i",i);
[self setNeedsDisplay:YES];
}
But the object being is not being added to the array. it never returns any value other than 0 in the NSLog function. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题是你的
init
方法。你完全错了,它应该看起来像这样:你的问题是你没有调用
super
的 init 并将其分配给self
和 然后设置数组
。您在获得正确的对象之前就分配了array
,然后您甚至没有返回array
已设置的任何内容,而是返回了以下结果超类的init
方法。然后,当您记录array.count
时,array
为nil
,因此i
变为0< /code> (因为在这种情况下消息
nil
返回 0)。Your problem is your
init
method. You've got it quite wrong and it should look like this:Your problem is that you're not calling
super
's init and assigning that toself
and then setting uparray
. You're assigningarray
before you've even got a proper object and then you're not even returning anything thatarray
has been set on, but rather returning the result of the super-class'sinit
method. Then when you go to logarray.count
,array
isnil
and hencei
becomes0
(because messagingnil
returns 0 in this circumstance).