本文共 6804 字,大约阅读时间需要 22 分钟。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #import <Foundation/Foundation.h> @interface Car : NSObject @property BOOL running; @end Car.m #import "Car.h" @implementation Car @synthesize running = _running; //Xcode 4.4以上可选 @end |
1 2 3 4 5 6 7 8 9 | -( BOOL )running { return _running; } -( void )setRunning:( BOOL )running { _running = running; } 当用 |
1 2 3 | Car *honda = [[Car alloc] init]; honda.running = YES ; NSLog (@ "%d" ,honda.running); |
1 | @property (getter=isRunning) BOOL running; |
1 2 3 4 | Car *honda = [[Car alloc] init]; honda.running = YES ; NSLog (@ "%d" ,honda.running); NSLog (@ "%d" ,[honda isRunning]); |
1 2 3 4 5 6 7 8 | #import <Foundation/Foundation.h> @interface Car : NSObject @property (getter=isRunning, readonly ) BOOL running; -( void )startEngine; -( void )stopEngine; @end |
1 2 3 4 5 6 7 8 | -( void )startEngine { _running = YES ; } -( void )stopEngine { _running = NO ; } |
1 2 3 4 | Car *honda = [[Car alloc] init]; // honda.running = YES; NSLog (@ "%d" ,honda.running); honda.running = NO ; |
1 | @property ( nonatomic ) NSString *model; //设置非原子性 |
1 2 3 4 | @interface Person : NSObject @property ( nonatomic ) NSString *name; @end |
1 2 3 4 5 6 7 8 9 | #import "Person.h" @implementation Person -( NSString *)description { return self .name; } @end |
1 2 3 4 5 6 7 8 9 10 | #import <Foundation/Foundation.h> #import "Person.h" @interface Car : NSObject @property ( nonatomic ) NSString *model; @property ( nonatomic ,strong) Person *driver; @end |
1 2 3 4 5 6 7 8 | Person *john = [[Person alloc] init]; john.name = @ "John" ; Car *honda = [[Car alloc] init]; honda.model = @ "Honda Civic" ; honda.driver = john; NSLog (@ "%@ is driving the %@" ,honda.driver,honda.model); |
1 2 3 4 5 6 7 8 9 10 | #import <Foundation/Foundation.h> @class Car; @interface Person : NSObject @property ( nonatomic ) NSString *name; @property ( nonatomic ,strong)Car *car; @end |
1 2 3 4 5 6 7 | Person *john = [[Person alloc] init]; john.name = @ "John" ; Car *honda = [[Car alloc] init]; honda.model = @ "Honda Civic" ; honda.driver = john; john.car = honda; //添加这行 NSLog (@ "%@ is driving the %@" ,honda.driver,honda.model); |
1 | @property ( nonatomic ,weak)Car *car; |
7、copy属性
1 2 3 4 5 6 7 8 9 | Car *honda = [[Car alloc] init]; honda.model = @ "Honda Civic" ; NSMutableString *model = [ NSMutableString stringWithString:@ "Honda Civic" ]; honda.model = model; NSLog (@ "%@" ,honda.model); [model setString:@ "Nissa Versa" ]; NSLog (@ "%@" ,honda.model); //输出结果还是Honda Civic |
转载地址:http://giozx.baihongyu.com/