#import <Foundation/Foundation.h> @class Author; @interface Books : NSObject{ @private NSString *color; int book_id; NSString *box; Author *author; NSArray *relationbook; float price; @public NSString *name; } @property (nonatomic) int size; -(void) setBox:(NSString *) box; -(NSString *) box; -(NSString *) method; @end
#import "Books.h" @implementation Books @synthesize size=_size; -(void) setBox:(NSString *) _box{ box=_box; } -(NSString *) box{ return box; } -(NSString *) method{ return @"这个方法可以通过[],或者点语法调用"; } @end
#import <Foundation/Foundation.h> @interface Author : NSObject @property (nonatomic,copy) NSString *name; @end
#import "Author.h" @implementation Author @synthesize name=_name; @end
Books *book=[[Books alloc] init]; //当属性为public时,可以通过指针来操作,kvo,kvc操作 book->[email protected]"iso开发"; NSLog(@"%@",book->name); [book setValue:@"iphone" forKeyPath:@"name"]; NSLog(@"%@",[book valueForKey:@"name"]); //当属性为private时,可以用property和synthesize来自动生成get,set方法,然后通过点语法或者调用自动生成方法来操作 book.size=12; NSLog(@"%d",book.size); [book setSize:14];//自动生成的set方法 NSLog(@"%d",[book size]);//自动生成的get方法 [book setValue:[NSNumber numberWithInt:2323] forKeyPath:@"size"]; NSLog(@"%@",[book valueForKey:@"size"]); //当属性为private时,可以手动生成,然后通过点语法或者调用方法来操作 NSString *[email protected]"书的内容"; book.box=content; NSLog(@"%@",book.box); [book setBox:content]; NSLog(@"%@",[book box]); [book setValue:@"来说" forKeyPath:@"box"]; NSLog(@"%@",[book valueForKey:@"box"]); //声明普通方法可以通过点语法调用或者[]调用 NSLog(@"%@",[book method]); NSLog(@"%@",book.method); //当属性为private时,可以通过kvo,kvc,即下面方式访问 //-----属性为普通类型操作 [book setValue:@"android开发" forKey:@"name"]; [book setValue:@"whilte" forKey:@"color"]; NSLog(@"%@:%@",[book valueForKey:@"name"],[book valueForKey:@"color"]); //----属性为自定义对象操作1--对象 Author *author=[[Author alloc] init]; [email protected]"caicai"; [book setValue:author forKey:@"author"]; Author *author2=[book valueForKey:@"author"]; NSLog(@"%@",author2.name); //----属性为自定义对象操作2--对象--路径访问 [book setValue:@"caitou" forKeyPath:@"author.name"]; NSLog(@"%@",[book valueForKeyPath:@"author.name"]); //----属性为自定义对象操作2--对象数组--路径访问 NSMutableArray *relationBook=[NSMutableArray arrayWithCapacity:3]; for (int i=0; i<3; i++) { Books *book=[[Books alloc] init]; NSString *name=[NSString stringWithFormat:@"job_%d",i]; [book setValue:name forKeyPath:@"name"]; [book setValue:@(12+i) forKeyPath:@"price"]; [relationBook addObject:book]; } [book setValue:relationBook forKeyPath:@"relationbook"]; NSArray *names=[book valueForKeyPath:@"relationbook.name"]; NSLog(@"%@",names); //kvc简单运算 sum max avg count NSLog(@"%@",[book valueForKeyPath:@"[email protected]"]); NSLog(@"%@",[book valueForKeyPath:@"[email protected]"]); NSLog(@"%@",[book valueForKeyPath:@"[email protected]"]); NSLog(@"%@",[book valueForKeyPath:@"[email protected]"]);
时间: 2024-12-29 23:25:40