Reputation: 2710
I am adding multiple instances of subclass of NSOperation in a for loop:
NSMutableArray * operations = [[NSMutableArray alloc]initWithCapacity:0];
for(int i =1; i<81;i++){
[operations addObject:[[PDFGenerator alloc]initWithPageNumber:i andPDFParser:pdf]];
}
[_queue addOperations:operations waitUntilFinished: NO];
in PDFGenerator I have a variable that stores the current page number for the operation.
@implementation PDFGenerator
int pageCounter;
In the main method of the PDFGenerator I am logging the current page number and it prints 80 for ALL the operations!
I already fixed by using @property for the current page count, but I am trying to understand why it's happening. Any ideas? thanks!
Upvotes: 0
Views: 96
Reputation: 18932
When you just use:
int pageCounter;
You are creating a global variable. Presuming you set this at each iteration, then refer to it in your PDFGenerator methods, it will always use the last value it was set to.
Example:
// Bar.h
@interface Bar : NSObject
FOUNDATION_EXPORT int someThing;
@end
// Bar.m
@implementation Bar
int someThing;
@end
// Foo.m
#import "Foo.h"
#import "Bar.h"
@implementation Foo
- (void)doSomething
{
++someThing;
}
@end
That's totally valid code, and calls to [Foo doSomething]
increment someThing
.
If you wanted an instance variable, it would look like this:
@interface Bar()
{
int someThing;
}
@end
@implementation Bar
- (void)doSomething
{
++someThing;
}
@end
In this case someThing
is defined as an instance variable (not a global variable). It is an accessible part of objects of the Bar
.
Upvotes: 1