2012-12-10 92 views
0

這似乎是我有一個問題,不知道我是否正確執行此操作,因爲我只是開始目標c。Objective-C NSMutableArray不添加對象

現在我有兩個文件

Stores.h

#import<Foundation/Foundation.h> 
#import<MapKit/MapKit.h> 

@interface Stores: NSObject 

@property(nonatomic,strong) NSString *storeName; 
@property(nonatomic,strong) NSMutableArray *MenuItems; 

@end 

Stores.m

#import "Stores.h" 

@synthesize storeName,MenuItems; 

@end 

Menu.h

#import<Foundation/Foundation.h> 


@interface Menu: NSObject 

@property(nonatomic,strong) NSString *MenuItemDescription; 
@property(nonatomic) int MenuItemPrice; 

@end 

Menu.m

#import "Menu.h" 

@synthesize MenuItemDescription,MenuItemPrice; 

@end 

ViewController.m

#import "ViewController.h" 
#import "Stores.h" 
#import "Menu.h" 

@interface ViewController() 

@end 

@implementation ViewController 

NSMutableArray *stores; 

-(void) viewDidLoad 
{ 
    [super viewDidLoad]; 

    stores = [[NSMutableArray alloc]init]; 

    Stores *store = [[Stores alloc]init]; 

    [store setStoreName:@"Store1"]; 
    Menu *menuItem = [[Menu alloc]init]; 
    [menuItem setMenuItemDescription:@"Item1"]; 
    [menuItem setMenuItemPrice: 7] 

    [store.MenuItems addObject:menuItem]; //won't add menuItem to store.MenuItems 

    [stores addObject:store]; 

} 

@end 

所以也沒有結束添加任何對象來存儲。 如果我在調試中運行它,它說MenuItems有零個對象。 我知道我做錯了,但就像我說我是iOS新手。

+1

在-init,商店需要初始化它的陣列。 – CodaFi

回答

1

你沒有(至少在你顯示的代碼中)alloc/create/assign MenuItems,所以它仍然是零。在nil上調用addObject(或任何東西)只是一個無操作。

試試這個

Stores *store = [[Stores alloc]init]; 
store.MenuItems = [NSMutableArray arrayWithCapacity: 10]; 
+0

編輯:現在似乎工作,謝謝。 – Claud