Object-C学习代码【类扩展的学习】

本文详细介绍了Objective-C中的类扩展概念及其使用方法。通过一个具体的示例,展示了如何定义类扩展来添加私有属性和方法,并解释了这些成员的可见性和访问限制。
//
//  Things.h
//  ClassExtension
//
//  Created by on 14-9-10.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Things : NSObject
@property (assign) NSInteger thing1;
@property (readonly, assign) NSInteger thing2;

- (void) resetAllValues;
@end



//
//  Things.m
//  ClassExtension
//
//  Created by on 14-9-10.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "Things.h"

// 类扩展,注意声明方式
@interface Things ()
{
    NSInteger thing4;
}
// 这里的特性还有assign:默认,引用计数不增加
// retain:引用计数增加1
// 原子性:atomic默认。
// 非原子性:nonatomic
// atomic是OC中的一种线程保护技术,是防止在未完成的时候被另外一个线程使用,造成数据错误
// 这里将原来的readonly改成了readwrite
@property (readwrite, assign) NSInteger thing2;
@property (assign) NSInteger thing3;
@end

// 这里是Things的实现
@implementation Things
@synthesize thing1;
@synthesize thing2;
@synthesize thing3;

- (void) resetAllValues {
//    self.thing1是调用了setter方法
    self.thing1 = 200;
    self.thing2 = 300;
    self.thing3 = 400;
//     这是给thing4变量赋值
    thing4 = 5;
}

- (NSString *) description {
    NSString *desc = [NSString stringWithFormat: @"%ld %ld %ld",
                      (long)thing1, (long)thing2, (long)thing3];
    return desc;
} // description
@end



//
//  main.m
//  ClassExtension
//
//  Created by 吴家锋 on 14-9-10.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Things.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        Things *things = [[Things alloc] init];
        things.thing1 = 1;
//        这里调用thing2的setter方法会出错,因为thing2特性为readonly
//        readwrite特性是在Things.m文件中的类扩展定义的,只能在Things.m中访问,为私有
//        类扩展都为私有
//        things.thing2 = 2;
        NSLog(@"%@", things);
        [things resetAllValues];
        NSLog(@"%@", things);
    }
    return 0;
}


转载于:https://my.oschina.net/are1OfBlog/blog/312156

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值