对象和方法之间的关系
1.对象作为方法的参数
#import <Foundation/Foundation.h>
@interface Person : NSObject { @public int _age; NSString *_name; } -(void)displayPerson:(Person *) person; @end
@implementation Person
-(void)displayPerson:(Person *) person{
NSLog(@"名字:%@ 年龄:%d",person->_name,person->_age); }
@end int main(){
Person *p1 = [Person new]; Person *p2 = [Person new];
p1->_name = @"Star"; p1->_age =18;
p2->_name = @"Jack"; p2->_age = 21;
[p1 displayPerson:p1]; [p2 displayPerson:p2];
}
2.对象作为方法的返回值
#import <Foundation/Foundation.h>
@interface Person : NSObject { @public int _age; NSString *_name; } -(void)displayPerson:(Person *) person; -(Person *)changeSex:(Person *) person; @end
@implementation Person
-(void)displayPerson:(Person *) person{
NSLog(@"名字:%@ 年龄:%d",person->_name,person->_age); }
-(Person *)changeSex:(Person *) person{
person->_age = 66; NSLog(@"名字: %@ 年龄: %d",person->_name,person->_age); return person; }
@end int main(){
Person *p1 = [Person new]; Person *p2 = [Person new];
p1->_name = @"Star"; p1->_age =18;
p2->_name = @"Jack"; p2->_age = 21;
[p1 displayPerson:p1]; [p2 changeSex:p2];
Person *p3 = [p2 changeSex:p2];//p3和p2指向的是同一个空间
NSLog(@"名字: %@ 年龄: %d",p2->_name,p2->_age);
}
|