开发者

Creating global array & iterator

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 <NSFetchedRe开发者_高级运维sultsControllerDelegate>{
    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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜