Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to change the return value (for object) with Aspects's AspectPositionInstead
@interface MyObject : NSObject
@property NSString *name;
@end
@implementation MyObject
-(void)dealloc
{
NSLog(@"dealloc");
}
@end
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSError *error = nil;
[self aspect_hookSelector:@selector(getMyObject) withOptions:AspectPositionInstead usingBlock:^(id<AspectInfo> info){
NSInvocation *invocation = info.originalInvocation;
__unsafe_unretained MyObject *original = nil;
[invocation invoke];
[invocation getReturnValue:&original];
NSAssert([original.name isEqualToString:@"AAAAA"], @"");
MyObject *new = [[MyObject alloc] init];
new.name = @"BBBBB";
objc_setAssociatedObject(invocation, _cmd, new, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[invocation setReturnValue:&new];
} error:&error];
for (int i = 0; i < 100; i++) {
MyObject *a = [self getMyObject];
NSAssert([a.name isEqualToString:@"BBBBB"], @"");
}
return YES;
}
- (MyObject*)getMyObject
{
MyObject *a = [[MyObject alloc] init];
a.name = @"AAAAA";
return a;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.