由于我无法在Objective-C中的类别中创建合成属性,因此我不知道如何优化以下代码:
@interface MyClass (Variant)
@property (nonatomic, strong) NSString *test;
@end
@implementation MyClass (Variant)
@dynamic test;
- (NSString *)test {
NSString *res;
//do a lot of stuff
return res;
}
@end
Run Code Online (Sandbox Code Playgroud)
该测试方法被调用运行时多次,我做了很多的东西来计算结果.通常使用合成属性我会在第一次调用方法时将值存储在IVar _test中,并且下次只返回此IVar.我该如何优化上面的代码?
如果我在类别实现中使用objc_setAssociatedObject/objc_getAssociatedObject将模拟实例变量存储在setter方法中,那么我将如何访问getter方法中的键,因为setter方法中声明的任何变量都不在getter方法的范围内?
编辑:为了澄清,如果我使用以下模式,我应该在哪里声明STRING_KEY,以便我可以在setter和getter方法中使用它.
@interface NSView (simulateVar)
-(void)setSimualtedString:(NSString *)myString;
-(NSString *)simulatedString;
@end
@implementation NSView (simulateVar)
-(void)setSimualtedString: (NSString *)myString
{
objc_setAssociatedObject(self, &STRING_KEY, myString, OBJC_ASSOCIATION_RETAIN);
}
-(NSString *)simulatedString
{
return (NSString *)objc_getAssociatedObject(self, &STRING_KEY);
}
@end
Run Code Online (Sandbox Code Playgroud) 我想在NSURLSession上创建一个类别.该应用程序编译好,但当我尝试调用我得到的类别方法
-[__NSCFURLSession doSomething]: unrecognized selector sent to instance 0xbf6b0f0
<unknown>:0: error: -[NSURLSession_UPnPTests testCategory] : -[__NSCFURLSession doSomething]: unrecognized selector sent to instance 0xbf6b0f0
Run Code Online (Sandbox Code Playgroud)
很奇怪,这是我为了显示问题而构建的测试类.NSString上的类别工作正常,但NSURLSession上的类别无法在运行时找到该方法.我怀疑这是内部的东西.
意见请:-)
#import <XCTest/XCTest.h>
@interface NSString (test)
-(void) doSomethingHere;
@end
@implementation NSString (test)
-(void) doSomethingHere {
NSLog(@"Hello string");
}
@end
@interface NSURLSession (test)
-(void) doSomething;
@end
@implementation NSURLSession (test)
-(void) doSomething {
NSLog(@"Hello!!!!");
}
@end
@interface NSURLSession_UPnPTests : XCTestCase
@end
@implementation NSURLSession_UPnPTests
-(void) testCategory {
[@"abc" doSomethingHere];
NSURLSession *session = [NSURLSession sharedSession];
[session doSomething];
}
@end
Run Code Online (Sandbox Code Playgroud) 是否可以通过Xcode在.nib/.xib中使用和设置任何类型的ID,可以在运行时查询以从代码中识别特定的视图实例?
特别是在我们的界面中拥有相同NSView子类的多个副本时,我们如何知道我们当前正在查看哪个?
我正在研究如何将属性(在这种情况下为整数)添加到所有UIView实例,无论它们是否是子类.是否使用objc_setAssociatedObject()并objc_getAssociatedObject()在一个类别中以适当的Apple认可方式执行此操作?
我听说过一些关注,这构成了"运行时黑客",并且可能导致难以追踪和调试的问题.有没有人见过这类问题?有没有更好的方法在UIView没有子类化的情况下向所有实例添加整数属性?
更新:我不能只使用tag,因为这需要在已经tag用于其他事情的代码库中使用.相信我,如果我能用tag它,我会的!