gpt4 book ai didi

objective-c - 将临时对象添加到 NSMutableArray

转载 作者:行者123 更新时间:2023-12-03 16:52:52 25 4
gpt4 key购买 nike

我有一个自定义类 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 之外的任何值。我做错了什么?

最佳答案

你的问题是你的init方法。你完全错了,它应该看起来像这样:

- (id)init {
if (self = [super init]) {
array = [NSMutableArray new];
}
return self;
}

你的问题是你没有调用super的init并将其分配给self然后然后设置数组。您在获得正确的对象之前就分配了 array ,然后您甚至没有返回 array 已设置的任何内容,而是返回了以下结果父类(super class)的 init 方法。然后,当您记录 array.count 时,arraynil,因此 i 变为 0 (因为在这种情况下消息 nil 返回 0)。

关于objective-c - 将临时对象添加到 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9344382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com