NSQueue操作奇怪的行为

时间:2013-07-09 16:26:35

标签: ios

我在for循环中添加了多个NSOperation子类的实例:

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];
PDFGenerator中的

我有一个变量,用于存储操作的当前页码。

@implementation PDFGenerator
int pageCounter;

在PDFGenerator的主要方法中,我正在记录当前页码并打印 80为所有操作!

我已经使用@property修复当前页数, 但我试图理解为什么会这样。有任何想法吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

当您使用时:

int pageCounter;

您正在创建一个全局变量。假设您在每次迭代时设置此项,然后在PDFGenerator方法中引用它,它将始终使用它设置的最后一个值。

示例:

// 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

这是完全有效的代码,并且调用[Foo doSomething]增加someThing

如果你想要一个实例变量,它将如下所示:

@interface Bar()
{
    int someThing;
}

@end

@implementation Bar
- (void)doSomething
{
    ++someThing;
}
@end

在这种情况下,someThing被定义为实例变量(不是全局变量)。它是Bar的对象的可访问部分。

相关问题