ios - 同一个头文件中的类和类扩展名(类别)
<p><p>当我查看 Cocoa Touch API 时,我可以在同一个头文件中找到一些与类别一起声明的类,例如</p>
<pre><code>@interface NSArray : NSObject <NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration>
@property (readonly) NSUInteger count;
// and some other properties
@end
@interface NSArray (NSExtendedArray)
@property (readonly, copy) NSString *description;
// and some other properties
@end
</code></pre>
<p>现在我正在尝试对我的类(class)做同样的事情,如下所示:</p>
<pre><code>@interface ARCTextbook : NSObject
@property (nonatomic) NSInteger ID;
@property (nonatomic) NSString *name;
@end
@interface ARCTextbook (Student)
@property (nonatomic) NSInteger studentID;
@property (nonatomic, getter=isUsed) BOOL used; // Used by a student?
@end
</code></pre>
<p>但是,当我尝试访问 <code>studentID</code> 或 <code>used</code> 属性时,出现无法识别的选择器错误。我错过了什么吗?</p>
<p>干杯。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>这是关联对象,您可以引用以下文档:</p>
<p> <a href="http://www.davidhamrick.com/2012/02/12/Adding-Properties-to-an-Objective-C-Category.html" rel="noreferrer noopener nofollow">http://www.davidhamrick.com/2012/02/12/Adding-Properties-to-an-Objective-C-Category.html</a> </p>
<p> <a href="https://stackoverflow.com/questions/7890414/how-to-store-not-id-type-variable-use-a-objc-getassociatedobject-objc-setassocia" rel="noreferrer noopener nofollow">How to store not id type variable use a objc_getAssociatedObject/objc_setAssociatedObject?</a> </p>
<p>ARCTextbook.h</p>
<pre><code>#import <Foundation/Foundation.h>
@interface ARCTextbook : NSObject
@property (nonatomic) NSInteger ID;
@property (nonatomic) NSString *name;
@end
@interface ARCTextbook (Student)
@property (nonatomic) NSInteger studentID;
@property (nonatomic, getter=isUsed) BOOL used; // Used by a student?
@end
</code></pre>
<p>ARCTextbook.m</p>
<pre><code>#import "ARCTextbook.h"
#import <objc/runtime.h>
@implementation ARCTextbook
@end
static NSString *kStudentID = @"kStudentID";
static NSString *kUsed = @"kUsed";
@implementation ARCTextbook (Student)
@dynamic studentID;
@dynamic used;
- (void)setStudentID:(NSInteger)aStudentID {
objc_setAssociatedObject(self, (__bridge const void *)(kStudentID), @(aStudentID), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSInteger)studentID {
return ;
}
- (void)setUsed:(BOOL)aUsed {
objc_setAssociatedObject(self, (__bridge const void *)(kUsed), @(aUsed), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)isUsed {
return ;
}
@end
</code></pre>
<p>ViewController.m</p>
<pre><code>#import "ViewController.h"
#import "ARCTextbook.h"
@implementation ViewController
- (void)viewDidLoad {
;
// Do any additional setup after loading the view.
ARCTextbook *t = [ init];
t.studentID = 2;
t.used = YES;
}
@end
</code></pre></p>
<p style="font-size: 20px;">关于ios - 同一个头文件中的类和类扩展名(类别),我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/28689164/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/28689164/
</a>
</p>
页:
[1]