Change this:
@implementation MyClass
NSString *testVar;
@end
to:
@implementation MyClass {
NSString *testVar;
}
// methods go here
@end
and you'll get what you expected.
As you had it, you are actually creating a global variable. The two global variables were combined into one by the linker which is why both changed when you set one. The variable in curly braces will be a proper (and private) instance variable.
Edit: After being downvoted for no apparent reason, I thought I'd point out the "old" way of doing things, and the new way.
The old way:
SomeClass.h
@interface SomeClass : UIViewController <UITextFieldDelegate> {
UITextField *_textField;
BOOL _someBool;
}
@property (nonatomic, assign) BOOL someBool;
// a few method declarations
@end
SomeClass.m
@implementation SomeClass
@synthesize someBool = _someBool;
// the method implementations
@end
Now the new and improved way with the modern Objective-C compiler:
SomeClass.h
@interface SomeClass : UIViewController
@property (nonatomic, assign) BOOL someBool;
// a few method declarations
@end
SomeClass.m
@interface SomeClass () <UITextFieldDelegate>
@end
@implementation SomeClass {
UITextField *_textField;
}
// the method implementations
@end
The new way has several advantages. The primary advantage is that none of the implementation specific details about the class appear in the .h file. A client has no need to know what delegates the implementation needs. The client has no need to know what ivars I use. Now, if the implementation needs a new ivar or it needs to use a new protocol, the .h file doesn't change. This mean less code gets recompiled. It cleaner and much more efficient. It also makes for easier editing. When I'm editing the .m file and realize I need a new ivar, make the change in the same .m file I'm already editing. No need to swap back and forth.
Also note the implementation no longer needs an ivar or @synthesize
for the property.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…