mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 17:41:41 +00:00
Add instance variable definition examples.
This commit is contained in:
parent
f15a2b5f78
commit
03ada8d975
@ -144,6 +144,7 @@ int main (int argc, const char * argv[])
|
||||
NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2];
|
||||
[mutableSet addObject:@"Hello"];
|
||||
[mutableSet addObject:@"Hello"];
|
||||
NSLog(@"%@", mutableSet); // prints => {(Hello)}
|
||||
|
||||
///////////////////////////////////////
|
||||
// Operators
|
||||
@ -281,11 +282,12 @@ int main (int argc, const char * argv[])
|
||||
// @end
|
||||
@interface MyClass : NSObject <MyProtocol>
|
||||
{
|
||||
int count;
|
||||
id data;
|
||||
// Instance variable declarations (can exist in either interface or implementation file)
|
||||
int count; // Protected access by default.
|
||||
@private id data; // Private access. (More convenient to declare in implementation file)
|
||||
NSString *name;
|
||||
}
|
||||
// Convenience notation to auto generate public getter and setter
|
||||
// Convenient notation to auto generate public access getter and setter
|
||||
@property int count;
|
||||
@property (copy) NSString *name; // Copy the object during assignment.
|
||||
@property (readonly) id data; // Declare only a getter method.
|
||||
@ -294,8 +296,16 @@ _count = 5;
|
||||
NSLog(@"%d", _count); // prints => 5
|
||||
// To access public variable outside implementation file, @property generates setter method
|
||||
// automatically. Method name is 'set' followed by @property variable name:
|
||||
[objInitVar setCount:10]; // objInitVar = random object instance @property resides in.
|
||||
NSLog(@"%@", [objInitVar count]); // prints => 10
|
||||
MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance.
|
||||
[myClass setCount:10];
|
||||
NSLog(@"%@", [myClass count]); // prints => 10
|
||||
// You can customize the getter and setter names instead of using default 'set' name:
|
||||
@property (getter=countGet, setter=countSet:) int count;
|
||||
[myClass countSet:32];
|
||||
NSLog(@"%i", [myClass countGet]); // prints => 32
|
||||
// For convenience, you may use dot notation to set object instance variables:
|
||||
myClass.count = 45;
|
||||
NSLog(@"%i", myClass.count); // prints => 45
|
||||
|
||||
// Methods
|
||||
+/- (return type)methodSignature:(Parameter Type *)parameterName;
|
||||
@ -310,8 +320,9 @@ NSLog(@"%@", [objInitVar count]); // prints => 10
|
||||
@end
|
||||
|
||||
// Implement the methods in an implementation (MyClass.m) file:
|
||||
|
||||
@implementation MyClass
|
||||
@implementation MyClass {
|
||||
long count; // Private access instance variable.
|
||||
}
|
||||
|
||||
// Call when the object is releasing
|
||||
- (void)dealloc
|
||||
|
Loading…
Reference in New Issue
Block a user