0

I am attempting to load up an entire array of NSManagedObjects into an NSArray, then use an integer iterator to iterate through the array when a button is tapped. xCode seems to dislike declaring the integer and NSArray in the .h, then used throughout different methods in the .m.

I was wondering what the appropriate path an experienced developer would take in solving such a problem.

The flow would be: 1. Load data into array. 2. Set label using information at index 0. int i = 0; 3. User taps button; i++, retrieve element at index 1.

and so on until the end of the array, or the user stops tapping the button.

Edited:

This is the code that works, but I feel is incorrect:

XYZViewController.h

@interface XYZViewController : UIViewController <NSFetchedResultsControllerDelegate>{
    int index;  
}

XYZViewController.m

import "XYZViewController.h"

- (void)function1{
    index = 0;
}

- (void)function2{
    index++;
}

-(void)function3{
    NSManagedObject *obj = [results objectAtIndex:index];
}

Is this actually correct? It works, but not elegant; not at all.

Oh Danny Boy
  • 4,857
  • 8
  • 56
  • 88

2 Answers2

1

Did you declare the integer and NSArray in your .h file outside of a class? if so, it would be defined in every compilation module that includes that file, which results in multiple symbols at linking time => error.

Solution: If you need the NSArray / int only in one .m file, move them there. Otherwise declare them as extern in the .h, and define them in exactly 1 .m file, like this:

// 1.h
extern int myInt;

// 1.m
#include "1.h"
int myInt;
// Use myInt

// 2.m
#include "1.h"
// Use myInt
king_nak
  • 11,313
  • 33
  • 58
  • I have tried using extern but seem to receive $non_lazy_ptr). The idea is to declare the int in .h, then use it in three separate functions in the .m (functions: one where it gets initialized, one to iterate, one to retrieve index.) – Oh Danny Boy Jun 04 '10 at 13:52
  • Btw, it's only fair to say that using just "int myInt" works, but I feel this is incorrect. – Oh Danny Boy Jun 04 '10 at 13:54
  • @ Mr.: The `extern` won't work since you are trying to put it in the `@implementation` section. This is why he asked `Did you declare the integer and NSArray in your .h file outside of a class?` -- I think the code you wrote in your example is good, since the variable remains private from external units which don't need it. – Senseful Jun 04 '10 at 14:29
1

The code you wrote is correct since you want to keep the visibility of the variable as private as possible. In this case it seems like you only need this variable in the XYZViewController.m file. In fact, you may want to consider prefixing it with @private to make it even less visible to other units.

Community
  • 1
  • 1
Senseful
  • 86,719
  • 67
  • 308
  • 465