Junior — Middle
Can safety be guaranteed when declaring instance variables in Objective-C?
sobes.tech AI
Answer from AI
In Objective-C, variable safety when declaring instance variables is not guaranteed by the language itself. Instance variables are just class fields, and access safety depends on how you organize access and synchronization.
In multithreaded environments, to ensure safe access to instance variables, synchronization mechanisms such as @synchronized, NSLock, or other tools should be used.
Example of using @synchronized to protect access:
@interface MyClass : NSObject {
NSInteger _counter;
}
- (void)incrementCounter;
- (NSInteger)getCounter;
@end
@implementation MyClass
- (void)incrementCounter {
@synchronized(self) {
_counter++;
}
}
- (NSInteger)getCounter {
@synchronized(self) {
return _counter;
}
}
@end
Thus, safety in declaring instance variables is not automatic but achieved through proper access management.