setting an array from another view in objective c

100 views Asked by At

I have a class which can be accessed from all other pages just like facebook chat head bubble.Its a cart in my application.Items to the cart could be added from different views. HAve tried with NSNotification and is not working.The array inside the cart view is gettig as null.Any help?What i tried is:

-(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];
}

And in the cart view,

  - (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

There are 2 answers

0
anjani kp On

If you aren't using ARC, you might want to change the following line,

NSDictionary *dict = [notification userInfo];

To;

NSDictionary *dict = [notification userInfo] retain];
0
samir On

Your array exist just in the addCart method's scope. try like this :

-(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.
}

and you retrieve your array, you can do like this :

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

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