2011-03-26 31 views
1

作爲我的問題的演示,我創建了一個小例子:我創建了一個新的基於視圖的應用程序,然後將按鈕添加到xib並將其連接到一個IBAction。然後我寫了這個類:Objective C中對象初始化的問題C

#import <Foundation/Foundation.h> 
@interface TaskGenerator : NSObject { 
    NSArray* mathPictures; 
} 

- (TaskGenerator*)init; 
@property(retain,nonatomic) NSArray* mathPictures; 

@end 

#import "TaskGenerator.h" 
@implementation TaskGenerator 

@synthesize mathPictures; 

- (TaskGenerator*)init 
{ 
    self = [super init]; 
    if (self) 
    { 
     mathPictures = [NSArray arrayWithObjects:@"0.png",@"1.png",@"2.png",@"3.png",@"4.png",@"5.png",nil]; 
    } 
    return self; 
} 
@end 

然後我修改了創建的viewController:

#import <UIKit/UIKit.h> 
#import "TaskGenerator.h" 

@interface NechapackaViewController : UIViewController { 
    TaskGenerator *taskGen; 
} 
-(IBAction)vypis:(id)sender; 
@property(nonatomic,retain) TaskGenerator *taskGen; 
@end 


#import "NechapackaViewController.h" 
#import "TaskGenerator.h" 
@implementation NechapackaViewController 

@synthesize taskGen; 

- (void)viewDidLoad { 
    taskGen = [[TaskGenerator alloc] init]; 
    printf("%d\n",[taskGen.mathPictures count]); 
    [super viewDidLoad]; 
} 

-(IBAction)vypis:(id)sender 
{ 
    printf("%d\n",[taskGen.mathPictures count]); 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
} 

- (void)dealloc { 
    [super dealloc]; 
} 

@end 

我不明白是爲什麼,點擊按鈕後,有一個與NSArray的一個問題,雖然我在viewDidLoad中初始化了這個NSArray,但它並未初始化。我怎麼能讓它爲我工作?我需要在加載視圖後初始化此TaskGenerator,然後我將以各種方法使用此對象。 請幫我解決這個問題。

+0

當問一個問題,你應該張貼,你得到什麼錯誤或意外的結果,以及崩潰日誌,如果你的程序崩潰。你說數組沒有被初始化,但不是*會發生什麼。 – ughoavgfhw 2011-03-27 00:06:53

回答

4

我假設您的應用程序崩潰與EXC_BAD_ACCESS。原因是mathPictures對象已被釋放並且不再有效。您使用arrayWithObjects:方法創建它,該方法返回一個自動釋放對象。當一個對象被自動釋放時,它被添加到一個池中,並且當該池被「排空」時,其中的每個對象都將收到一條release消息。由於陣列沒有被保留在其他地方,因此它被釋放,使得變量指向可用內存。要解決這個問題,你需要使用alloc/init方法來獲得一個保留的數組,或者在創建它之後自己保留該數組。

- (TaskGenerator*)init { 
    self = [super init]; 
    if (self) { 
     mathPictures = [[NSArray alloc] initWithObjects:@"0.png",@"1.png",@"2.png",@"3.png",@"4.png",@"5.png",nil]; 
    } 
    return self; 
} 

而且,在你的viewDidLoad方法,你應該調用超級實施第一

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    taskGen = [[TaskGenerator alloc] init]; 
    printf("%d\n",[taskGen.mathPictures count]); 
} 
-1

你需要的Alloc在聲明mathPictures &的NSArray:

NSArray *mathPictures = [[NSArray alloc] initWithObjects:@"0.png", @"1.png", @"2.png", ..., nil]; 

或者,你可以將下面的行內的viewDidLoad:

mathPictures = [[NSArray arrayWithObjects:@"0.png", @"1.png", @"2.png", ..., nil] retain]; 

此外,在viewDidLoad中,應在執行其他任務之前,[super viewDidLoad]是否是第一行?

0

您的@property聲明創建了一個正確保留該對象的setter方法。但是,當你直接分配給mathPictures實例變量時,你繞過了setter,所以數組不會被保留。相反,你應該用點語法使用屬性setter:

self.mathPictures = [NSArray arrayWithObjects:@"0.png",@"1.png",@"2.png",nil];