[英]Objective-C NSMutableArray not adding object
It seems like I have a problem and don't know if I'm doing this right since I'm just starting objective c. 似乎我有问题,不知道我是否做对了,因为我只是开始目标c。
Right now I have two files 现在我有两个文件
Stores.h 商店.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 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
So it doesn't end up adding any object to store. 因此,它最终不会添加任何要存储的对象。 If I run it in debug it says that MenuItems has zero objects.
如果我在调试中运行它,则表明MenuItems具有零个对象。 I know I'm doing something wrong but like I said I'm new to iOS.
我知道我做错了事,但就像我说过的,我是iOS新手。
You did not (at least in the code you show) alloc/create/assign MenuItems, so it will still be nil. 您没有(至少在显示的代码中)没有分配/创建/分配MenuItems,因此它仍然为零。 Calling addObject (or anything) on nil is just a no-op.
在nil上调用addObject(或其他任何方法)只是一个禁忌。
Try this 尝试这个
Stores *store = [[Stores alloc]init];
store.MenuItems = [NSMutableArray arrayWithCapacity: 10];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.