2012-02-18 72 views
1

我有我試圖添加一個NSMutableArray添加一個臨時對象到一個NSMutableArray

數組的自定義類MDRect是一個屬性:

@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之外的任何值。我究竟做錯了什麼?

回答

5

您的問題是您的init方法。你明白了完全錯誤的,它應該是這樣的:

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

你的問題是,你不叫super的init和分配,爲self然後設置array。你在分配array之前,你甚至沒有得到一個適當的對象,然後你甚至沒有返回任何array已經設置,而是返回超類init方法的結果。那麼當你去登錄array.count時,arraynil,因此i變成0(因爲在這種情況下消息傳遞nil返回0)。

+0

謝謝!這解決了我的問題! – 2012-02-18 23:30:29

相關問題