Category 中属性的使用

本文深入探讨了Objective-C中的Category机制,解释了其用于声明实例或类方法而非额外属性的功能,强调了Category中声明属性的有效性和局限性,并提供了一个实际的示例代码解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// XXTest.h
#import <Foundation/Foundation.h>

@interface XXTest : NSObject

@end

@interface XXTest (test)

@property (nonatomic, copy) NSString *name;

@end


// XXTest.m
#import "XXTest.h"
#import <objc/runtime.h>

@implementation XXTest

@end

@implementation XXTest (test)
@dynamic name;

char XXName;
- (NSString *)isName {
    return objc_getAssociatedObject(self, &XXName);
}

- (void)setName:(NSString *)name {
    objc_setAssociatedObject(self, &XXName, name, OBJC_ASSOCIATION_COPY);
}

@end

Category 能被用来声明实例或者类方法,但是通常不适合用来声明额外的属性。在Category中声明属性是有效的语法,但是不能声明额外的实例变量。这意味着编译器不会合成任何实例变量,也不会合成任何属性访问器方法。你可以编写自己的访问器方法的类的实现,但你无法跟踪的属性值,除非它已经由原来的存储类。

原文:

Categories can be used to declare either instance methods or class methods but are not usually suitable for declaring additional properties. It’s valid syntax to include a property declaration in a category interface, but it’s not possible to declare an additional instance variable in a category. This means the compiler won’t synthesize any instance variable, nor will it synthesize any property accessor methods. You can write your own accessor methods in the category implementation, but you won’t be able to keep track of a value for that property unless it’s already stored by the original class.

apple 官方文档

 

转载于:https://my.oschina.net/petsatan/blog/681181

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值