oc中的构造方法和description方法
来源:互联网 发布:java 网站源码 编辑:程序博客网 时间:2024/04/29 21:28
oc和其他面向对象语言一样,也支持构造方法,当我们初始化一个对象的时候传入这个构造方法需要的值,而oc中的description方法相当于Java中的tostring方法都来自于父类。
#import <Foundation/Foundation.h>
@interface Person :NSObject{
int _age;
int _no;
}
- (int)age;
-(void)setAge:(int)age;
-(int)no;
-(void)setNo:(int)no;
//声明一个构造方法
-(id)initWithAge:(int)age andNo:(int)no;//返回id,id代表任何对象
@end
#import "Person.h"
@implementation Person
-(int)age{
return_age;
}
-(int)no{
return_no;
}
-(void)setAge:(int)age{
_age=age;
}
-(void)setNo:(int)no{
_no=no;
}
-(id)initWithAge:(int)age andNo:(int)no{
//先调用父类的构造方法
//self=[super init];
if(self=[superinit]){//如果这里不判断,有可能会产生空对象,实际上是self!=niu
// _age=age;
// _no=no;
self.age=age;
self.no=no;
}
return self;
}
//重写父类的description方法
-(NSString *)description{
NSString *str=[NSStringstringWithFormat:@"age=%i and no=%i",_age,_no];
return str;
}
@end
int main(int argc,constchar * argv[])
{
@autoreleasepool {
Person *p=[[Person alloc]init];
//Person *p=[Person new]; oc中也有new关键字,alloc一个对象并init
[p initWithAge:25andNo:110];//利用构造方法初始化一个对象
NSLog(@"对象的地址是%@",p);//调用了description方法
//释放对象
[prelease];
}
return0;
}
self与动态方法、静态方法的关系
//在动态方法中self代表了调用方法的对象
-(void)selfMethod{
int age=self.age;
}
//在静态方法中表示调用方法的当前类
+(void)selfMethod2{
[selfalloc];//[Person alloc];
}
成员变量的作用域(默认是@protected)@publicNSString *name;//全局都可以访问
@privateNSString *tel;//只能在类内部访问
@protectedNSString *address;//只能在类内部和子类中访问
总结:1.因为在objectc中没有包,所以也不像java中一样存在包权限。
2.如果在.h文件中没有声明方法,而只在.m文件中实现,那么这个方法就是私有方法。
- oc中的构造方法和description方法
- OC中的description方法
- OC学习那点事:构造方法和description方法
- OC学习2——构造方法和description方法
- 黑马程序员-OC-自定义构造方法和description方法
- OC学习:重写构造方法和description方法
- 黑马程序员-------OC----构造方法和description方法
- 【OC】OC description方法
- OC中的构造方法
- OC基础语法学习4:自定义构造方法和description方法
- 0C-013.OC中的description方法
- oc中的id关键字和构造方法
- OC语言学习 (六) 继承、多态,构造方法,description方法
- 05自定义构造方法和description方法
- 自定义构造方法和description方法
- 自定义构造方法和description方法
- OC语言description方法和sel
- OC中description方法和sel
- spring回顾笔记
- storm培训视频
- HASH入门 POJ1840
- STL与多线程+写时拷贝
- UVA 608 - Counterfeit Dollar(直接枚举)
- oc中的构造方法和description方法
- js库
- Socket 编程(TCP)
- 搜索官方的一篇相关性文章分享
- NPOI读取Excel
- Warning: Variable 'a' cannot be saved to a MAT-file whose version is older than 7.3.
- Cannot open precompiled header file: 'Debug/xxoo.pch': No such file or directory
- 2014年的打算
- java.lang.NoSuchMethodError: org.slf4j.impl.StaticLoggerBinder.getSingleton()Lorg/slf4j/impl/Static