简体   繁体   中英

Objective-C ivar behaviour

I am puzzled by some behaviour I'm seeing in Objective-C.

I have a method as follows:

-(void)showFormWithId:(NSString*)formId andMode:(int)mode
{
    HPSModelForm* model = [HPSDbUtilities getForm:formId];
    HPSFormController* formVC = [ [ HPSFormController alloc ] init ];
    [(UINavigationController*) self.view.window.rootViewController pushViewController:formVC animated:YES];


}

Within the HPSFormController class my implementation contains the following:

@implementation HPSFormController
NSArray* _arrayOfPageNosWithSummaryElements;

ie _arrayOfPageNosWithSummaryElements is not a property, but is an ivar visible to any method within the HPSFormController class. It is not declared in the header file at all.

When I call showFormWithId the first time then _arrayOfPageNosWithSummaryElements is nil. However, when I call showFormWithId a second time then it seems to me that _arrayOfPageNosWithSummaryElements is not nil, but has the value from the previous instance of HPSFormController. I don't understand this - surely because the scope of the formVC is the showFormWithId method then the second time I call showFormWithId then a completely new instance of HPSFormController should be created with _arrayOfPageNosWithSummaryElements uninitialised and therefore set to nil?

What am I doing wrong? Thanks.

It's not actually in instance variable here at all (instance variables are declared in the interface section of a class). You're declaring a global variable, in the normal C sense.

@implementation HPSFormController
NSArray* _arrayOfPageNosWithSummaryElements;

is no ivar declaration but a declaration of a global variable. You have to use brackets:

@implementation HPSFormController {
   NSArray* _arrayOfPageNosWithSummaryElements;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM