Advertise with us

How to get class object index in NSMutableArray in Xcode?

Posted by  Ankita Pandey
 1411  View(s)
Rate this:
I have two controllers in our iPhone application. In one controller I have create a ImageCollection class and an NSMutableArray imgArray. after that I have stored ImageCollection objects into the imgArray. Now, I want to get the specific index of ImageCollection object which is stored in the imgArray.
Can anyone tell me how can I find the index of any specific object. Please provide me some code if possible as hint for me.
Thank You.
  1. Re: How to get class object index in NSMutableArray in Xcode?

    To get the index of object from the mutable array. For that- first of all import the FirstViewController (where you create ImageCollection class and array) in the SecondViewController and under the @interface create a property of NSIndexPath. like this:

    @interface SecondViewController:UIViewController
    @property NSIndexPath *indexPathOfImage;

    Now, go to the FirstViewController's implementation file import the SecondViewController. now, under the didSelectItemAtIndexPath: method of CollectionView create a reference of second view controller using storyboard like this:

    SecondViewController *secondController = [self.storyborad instantiateViewControllerWithIdentifier:@"SecondViewController"];

    now, when ever any collection view cell will be clicked, collection view method didSelectItemAtIndexPath: will be called which has the indexPath. Now we will assign it in the second view controller property indexPathOfImage, like this:

    -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath*)indexPath
      SecondViewController *secondController = [self.storyborad instantiateViewControllerWithIdentifier:@"SecondViewController"];
      secondController.indexPathOfImage = indexPath;

    Now, we can use it in the second view controller to get the index from imgArray, like this:

    SecondViewController *secondViewController * [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    ImageCollection *imgCollection = [secondViewController.imgArray objectAtIndex:_indexPathOfImage];

    that's it. I hope it will be helpful for you.