Home > DeveloperSection > Forums > How to get class object index in NSMutableArray in Xcode?
Ankita Pandey
Ankita Pandey

Total Post:183

Posted on    January-23-2016 6:41 AM

 iPhone iPhone  Ios  Objective C 

 1 Reply(s)
 572  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.

Tarun Kumar

Total Post:214

Posted on    January-23-2016 7:20 AM

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.

Don't want to miss updates? Please click the below button!

Follow MindStick