Category 中属性的使用

 2023-09-05 阅读 84 评论 0

摘要:2019独角兽企业重金招聘Python工程师标准>>> // XXTest.h #import <Foundation/Foundation.h>@interface XXTest : NSObject@end@interface XXTest (test)@property (nonatomic, copy) NSString *name;@end// XXTest.m #import "XXTe

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

// 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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/1111.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息