从目标c中的另一个视图设置数组

时间:2013-12-08 10:03:37

标签: objective-c nsarray nsnotification

我有一个类可以从所有其他页面访问,就像Facebook聊天头泡。在我的应用程序中有一个购物车。可以从不同的视图添加到购物车的项目。已经尝试过使用NSNotification并且无法正常工作。购物车视图中的数组是gettig为null。任何帮助?我尝试的是:

-(IBAction)addToCart:(id)sender{
    NSMutableArray *itemToCart=[[NSMutableArray alloc]init];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:gearImgView.image forKey:@"equipImage"];
    [dict setObject:nameLbl.text forKey:@"name"];
     [dict setObject:priceLbl.text forKey:@"price"];
    [dict setObject:self.shopifyIDString forKey:@"shopifyID"];
    [itemToCart addObject:dict];

   [[NSNotificationCenter defaultCenter] postNotificationName:@"equipmentSelected" object:nil userInfo:dict];
}

在购物车视图中,

  - (void)viewDidLoad
    {

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadEquipmentview:) name:@"equipmentSelected" object:nil];
     [super viewDidLoad];
    }

-(void)loadEquipmentview:(NSNotification *)notification{

    NSDictionary *dict = [notification userInfo];

    NSString *shopifyID = [dict objectForKey:@"shopifyID"];

      NSLog(@"%@",dict);
}

2 个答案:

答案 0 :(得分:0)

如果您不使用ARC,则可能需要更改以下行

NSDictionary *dict = [notification userInfo];

要;

NSDictionary *dict = [notification userInfo] retain];

答案 1 :(得分:0)

您的数组仅存在于addCart方法的范围内。试试这样:

-(IBAction)addToCart:(id)sender{
    NSMutableArray *itemToCart=[[NSMutableArray alloc]init];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:gearImgView.image forKey:@"equipImage"];
    [dict setObject:nameLbl.text forKey:@"name"];
     [dict setObject:priceLbl.text forKey:@"price"];
    [dict setObject:self.shopifyIDString forKey:@"shopifyID"];

    [itemToCart addObject:dict];

   // Create an other dictionnary to hold the array of dictionary
   NSMutableDictionary *otherDict = [NSMutableDictionary dictionary];
  otherDict[@"yourArrayKey"] = itemToCart;

// The you post the otherDict
[[NSNotificationCenter defaultCenter] postNotificationName:@"equipmentSelected" object:nil userInfo:otherDict]; //be careful here, you should post the otherDict and not the dic.
}

你检索你的数组,你可以这样做:

-(void)loadEquipmentview:(NSNotification *)notification{

    NSDictionary *dict = [notification userInfo];
    NSMutableArray *array = dic[@"yourArrayKey"];
   ....
}