What are the differences (if any) between the following Objective-c 2.0 code snippets:
// in MyClass.h
@interface MyClass
@private
NSString *myString;
@end
and
// in MyClass.m
@interface MyClass ()
@property (nonatomic, copy) NSString *myString;
@end
@implementation MyClass
@synthesize myString;
@end
A property can be backed by an instance variable, but you can also define the getter/setter to do something a bit more dynamic, e.g. you might define a lowerCase property on a string which dynamically creates the result rather than returning the value of some member variable.
They are tied to a particular object instance of the class, therefore, the contents of an instance variable are totally independent of one object instance to others. Class Variable: It is basically a static variable that can be declared anywhere at class level with static.
Instance variables are declared right after the class declaration. They usually start with private then the type of the variable and then a name for the variable. Private means only the code in this class has access to it. The Person class declares 3 private instance variables: name, email, and phoneNumber.
Category and extension both are basically made to handle large code base, but category is a way to extend class API in multiple source files while extension is a way to add required methods outside the main interface file.
The ivar (first one) is a plain variable that cannot be accessed out of the scope of an implementation of the interface it's created in (if @private directive is used) and has no synthesized accessor methods.
The property (second one) is a wrapped ivar and something that can always be accessed via instantiating a class and has accessor methods synthesized (if @synthesize directive is being used)
MyClass *class = [[MyClass alloc] init];
[class setMyString:@"someString"]; //generated setter
NSString *classString = [class myString]; //generated getter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With