2016-11-13 24 views
-1

我試圖將封裝到應用中(關於這是什麼代碼是應該做的,看到here的解釋)......這是類「A」的代碼:封裝造成死機

.H文件

@interface ExportBookData : NSObject { 

@public NSArray *booksArray; 
@public NSMutableDictionary *builtFileList; 
@public NSMutableArray *exportData; 
} 

- (id)initWithCategory: (NSString*) booksellerID; 

@end 

這是.m文件代碼:

.m文件

@implementation ExportBookData 

-(id)initWithCategory: (NSString*) booksellerID { 

return (id)booksellerID; 
} 

@end 

這是在「B」級方法(.m文件)的使用該封裝的數據的開頭:

ExportBookData *abe = [[ExportBookData alloc] initWithCategory:@"ABE"]; 
abe->builtFileList = [NSMutableDictionary dictionary]; <- crash on this line 
abe->exportData = [NSMutableArray arrayWithCapacity:abe->booksArray.count]; 

if(cbvABE.checked) { 

我得到上的代碼的第2行以下錯誤指示:

enter image description here

由於我是使用封裝的noob,我沒有看到我做錯了什麼。我跟隨了幾個與我的代碼類似的例子;我做錯了什麼導致這次崩潰?

+0

[NSMutableDictionary dictionary]不分配新的字典。嘗試] [NSMutableDictionary alloc] initWithCapacity:10];例如。 –

+0

這樣做([[NSMutableDictionary alloc] initWithCapacity:10];),同樣的錯誤... – SpokaneDude

+0

哦,對不起,你的init必須先調用超級init,構造函數必須返回self。 –

回答

3

這裏有很多問題。

首先,不要聲明公共實例變量。使用屬性並僅用於您希望其他類可以訪問的值。

@interface ExportBookData : NSObject 

@property(nonatomic, strong) NSArray *booksArray; 
@property(nonatomic, strong) NSMutableDictionary *builtFileList; 
@property(nonatomic, strong) NSMutableArray *exportData; 

- (id)initWithCategory: (NSString*) booksellerID; 

@end 

現在你的ExportBooksData init方法。

它需要:

-(id)initWithCategory: (NSString*) booksellerID { 
    self = [super init]; 
    if (self) { 
     // do something with booksellerID 
    } 

    return self; 
} 

基類的每一個方法init應該跟隨此一般模式。

現在你的其他代碼是不必要地使用->運算符。改爲使用接口提供的實際屬性:

ExportBookData *abe = [[ExportBookData alloc] initWithCategory:@"ABE"]; 
abe.builtFileList = [NSMutableDictionary dictionary]; 
abe.exportData = [NSMutableArray arrayWithCapacity:booksArray.count]; 

但是,外部代碼正在做所有這些都沒有意義。讓你的班級根據需要進行設置。所以,現在你init方法應該是:

-(id)initWithCategory: (NSString*) booksellerID { 
    self = [super init]; 
    if (self) { 
     self.builtFileList = [NSMutableDictionary dictionary]; 
     self.exportData = [NSMutableArray arrayWithCapacity:booksArray.count]; 

     // do something with booksellerID 
    } 

    return self; 
} 

現在你的其他代碼簡直變成:

ExportBookData *abe = [[ExportBookData alloc] initWithCategory:@"ABE"]; 

,而不需要設置的其他屬性。

還有很多你應該在這裏做的(如使用booksellerIDbooksArray),但這會讓你開始。

+0

嗨裏克...再次感謝...我總是感謝您的幫助和明確的解釋! 如果你不介意,我會給約翰點分數,因爲他很接近,即使是第一個評論是錯誤的,並且你有很多點(不是你不能使用更多!):D) ,但我認爲在這種情況下這是公平的事情。如果您不同意,請在將John標記爲答案之前發表評論。 – SpokaneDude

+1

當然。你投票給你認爲有幫助的答案。它甚至不必爲你自己的問題。如果您在搜索時碰巧找到有用的答案,那就投票吧。 – rmaddy

0

您的構造函數需要調用超級初始化才能正確初始化。然後你添加初始化代碼並最終返回自己;

(id) initWithCategory: (NSString*) booksellerID 
    { 
     self = [super init]; 
     if (self != nil) 
     { 
      myBookSellerID = booksellerID; 
     } 
     return self; 
    }