`
阿尔萨斯
  • 浏览: 4192093 次
社区版块
存档分类
最新评论

OC-方法之desription/alloc/init(2)

 
阅读更多
#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    @protected
    int _age;
}

- (void) setAge:(int)age;
- (int) age;


@end

@implementation Person

- (void) setAge:(int)age
{
    _age=age;
}

- (int) age
{
    return _age;
}

- (id) init
{
    if (self=[super init]) {
        self->_age=20;
    }
    return self;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"_age %d",_age];
}

@end

@interface Student : Person

@end

@implementation Student

- (id) init
{
    if (self=[super init]) {
        //use of undeclared identifier 'super'
        //super->_age=30;
        self->_age=30;
    }
    return self;
}

@end


int main()
{
    //相当于[Person new]
    Person *p=[[Student alloc] init];
    NSLog(@"%@",p);
    return 0;
}


1对象实例化包括两个步骤

-分配内存 -初始化变量

Student *stu=[Student alloc];表示为一个内存分配存储空间,并返回该空间的指针

[stu init];调用-(id) init 方法初始化对象.对象初始化前必须调用超类的init方法.

当我们需要初始化对象属性的时候,可以提供一个带有参数的构造方法,例如

[stu initWithAge:.... andScore:...];


2.当我们查看一个对象,主要是观察其内部属性的值,这时候向对象发送一条description消息.

重新该方法,以获取对象属性,类比JAVA 的toString();


分享到:
评论

相关推荐

    .NET获取枚举DescriptionAttribute描述信息性能改进的多种方法

    主要介绍了.NET获取枚举DescriptionAttribute描述信息性能改进的多种方法 的相关资料,需要的朋友可以参考下

    Android代码-Just a bar

    Desription selectedColor Selected state color for the BarItem unSelectedColor Unselected state color for the BarItem selectedIconColor Selected state color for the icon unSelectedIconColor ...

    php实现等比例压缩图片

    * desription 压缩图片 * @param sting $imgsrc 图片路径 * @param string $imgdst 压缩后保存路径 */ public function compressedImage($imgsrc, $imgdst) { list($width, $height, $type) = getimagesize($...

    PHP实现图片压缩的两则实例

    * desription 压缩图片 * @param sting $imgsrc 图片路径 * @param string $imgdst 压缩后保存路径 */ function image_png_size_add($imgsrc,$imgdst){ list($width,$height,$type)=getimagesize($imgsrc); $new_...

    uart.zip_ Verilog serial_between_uart verilog

    This Verilog file is a desription of an UART, which is a piece of computer hardware that translates data between parallel and serial forms.

    PHP等比例压缩图片的实例代码

    * desription 压缩图片 * @param sting $imgsrc 图片路径 * @param string $imgdst 压缩后保存路径 */ public function compressedImage($imgsrc, $imgdst) { list($width, $height, $type) = getimagesize($...

Global site tag (gtag.js) - Google Analytics