您的位置:首页 > 移动开发 > Objective-C

oc中的构造方法和description方法

2014-01-27 21:33 363 查看
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文件中实现,那么这个方法就是私有方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐