2011-10-08 55 views
0

我正在嘗試爲我的程序製作自定義HashTable。是的,我知道Xcode中已經有了一個HashTable類,但是對於這種情況我有一個自定義類。它應該很簡單,但是當我試圖在我的視圖控制器中使用它時,即使在調用初始化方法之後,調試器仍顯示其值爲「0x0」。下面的代碼:初始化自定義類的對象的問題

//header file HashTable.h 

#import <Foundation/Foundation.h> 


@interface HashTable : NSObject 
{ 
} 

-(void)initWithLength:(int)capacity; 
-(void)add:(NSObject*)object withName:(NSString*)name; 
-(id)getObjectFromIndex:(int)index; 
-(id)getObjectWithName:(NSString*)name; 

@end 


//main file HashTable.m 

#import "HashTable.h" 

@implementation HashTable 

NSMutableArray* values; 
NSMutableArray* markers; 

-(id)initWithLength:(int)capacity //Apparently, this never gets called 
{ 
    self = [super init]; 
    if (self) 
    { 
     values = [[NSMutableArray alloc] initWithCapacity:capacity]; 
     markers = [[NSMutableArray alloc] initWithCapacity:capacity]; 
    } 
    return self; 
} 

-(void)add:(NSObject*)object withName:(NSString*)name 
{ 
    [values addObject:object]; 
    [markers addObject:name]; 
} 

-(id)getObjectFromIndex:(int)index 
{ 
    return [values objectAtIndex:index]; 
} 

-(id)getObjectWithName:(NSString*)name 
{ 
    for (int i = 0; i < [markers count]; i++) 
    { 
     if ([[markers objectAtIndex:i] isEqualToString:name]) {return [values objectAtIndex:i];} 
    } 
    return [NSObject new]; 
} 

-(void)removeObjectFromIndex:(int)index 
{ 
    [values removeObjectAtIndex:index]; 
    [markers removeObjectAtIndex:index]; 
} 

-(void)removeObjectWithName:(NSString*)name 
{ 
    for (int i = 0; i < [markers count]; i++) 
    { 
     if ([[markers objectAtIndex:i] isEqualToString:name]) 
     { 
      [values removeObjectAtIndex:i]; 
      [markers removeObjectAtIndex:i]; 
      return; 
     } 
    } 
} 

-(BOOL)isEmpty 
{ 
    return [values count] == 0; 
} 

-(void)dealloc 
{ 
    [values release]; 
    [markers release]; 
    [super dealloc]; 
} 

@end 

然後我有一個使用哈希表視圖控制器的部分:

//header file 

#import <UIKit/UIKit.h> 

#import "HashTable.h" 

@interface Circuitry_LabViewController : UIViewController 
{ 
    HashTable* table; 
} 

@property(nonatomic, retain) HashTable* table; 

@end 

//main file 

#import "Circuitry_LabViewController.h" 

@implementation Circuitry_LabViewController 

@synthesize table; 

- (void)viewDidLoad 
{ 
    [table initWithLength:10]; 
    [super viewDidLoad]; 
} 

我看不到什麼,我在這裏失蹤。誰能幫忙?

回答

1

你的意思做這-viewDidLoad:

table = [[HashTable alloc] initWithLength:10]; 

有什麼地方告訴我,你這樣做是錯誤的。

+0

所以即使我在頭文件中聲明它,我仍然需要這樣做嗎? – RaysonK

+0

@RaysonK是的,你這樣做。 –

+0

好的,做到了,但它仍然是「0x0」。我也收到一個警告,說'表格可能無法識別'alloc''。我需要在HashTable中創建一個alloc方法嗎? – RaysonK