黑马程序员技术交流社区
标题:
oc中的对象使用
[打印本页]
作者:
vyqrvwgf
时间:
2015-11-3 21:02
标题:
oc中的对象使用
1.对象(object)
是系统中的基本运行实体,对象就是类类型的变量,定义一个类,就可以创建多个这个类的对象,一个类就是具有相同类型的对象的抽象。
2.对象的存储细节
假设有一个Person的类
当[Person new];
1)申请内存空间
2)初始化实例变量
3)返回内存空间的地
3.对象和方法之间的关系
1)对象作为方法的参数
#import <Foundation/Foundation.h>
@interface Person:NSObject
{
//公开属性,不安全
@public
//属性名前加上下划线
NSString *_name;
int _age;
}
-(void)displayPerson:(Person *)person;
@end
@implementation Person
//将Person类的对象作为Person类对象方法的形参
-(void)displayPerson:(Person *)person{
NSLog(@"姓名%@,年龄%d",person->_name,person->_age);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person1=[Person new];
Person *person=[Person new];
person1->_name=@"lazy";
person1->_age=25;
[person displayPerson:person1];
}
return 0;
}
复制代码
2)对象作为方法的返回值
#import <Foundation/Foundation.h>
@interface Person:NSObject
{
@public
NSString *_name;
int _age;
}
-(Person *)chageAge:(Person *)person;
@end
@implementation Person
//返回Person类对象
-(Person *)chageAge:(Person *)person{
person->_age=20;
return person;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person1=[Person new];
Person *person=[Person new];
person1->_name=@"lazy";
person1->_age=25;
[person chageAge:person1];
NSLog(@"姓名:%@,年龄:%d",person1->_name,person1->_age);
}
return 0;
}
复制代码
3)对象作为参数连续传递
#import <Foundation/Foundation.h>
@interface Bullet:NSObject
{
@public
int _bulletCount;
}
@end
@implementation Bullet
@end
@interface Gun : NSObject
-(void)shoot:(Bullet*)bullet;
@end
@implementation Gun
-(void)shoot:(Bullet *)bullet{
NSLog(@"正在发射子弹");
bullet->_bulletCount--;
}
@end
@interface Person : NSObject
-(void)fire:(Gun*)gun and:(Bullet*)bullet;
@end
@implementation Person
-(void)fire:(Gun *)gun and:(Bullet*)bullet{
NSLog(@"人在开枪");
[gun shoot:bullet];
}
@end
int main(){
Person *lazy=[Person new];
Gun *ak=[Gun new];
Bullet *b=[Bullet new];
[lazy fire:ak and:b];
return 0;
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2